Created
June 30, 2012 07:18
-
-
Save ww24/3022772 to your computer and use it in GitHub Desktop.
Array.prototype.depth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 配列の深さ(次元)を返す | |
Array.prototype.depth = function () { | |
function isArray(a) { | |
return typeof(a) === "object" && (a instanceof Array); | |
}; | |
var arr = this; | |
return (function(a, b) { | |
a = a || arr; | |
b = b || 0; | |
if (isArray(a) && a.length) { | |
b++; | |
var c = []; | |
for (var i=0,l=a.length; i<l; i++) { | |
c[c.length] = arguments.callee(a[i], b); | |
} | |
return Math.max.apply(null, c); | |
} | |
return b; | |
})(); | |
}; | |
// Usage | |
console.log([8,[[9]]].depth()); | |
// -> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment