查找JavaScript数组的维数 [英] Find the dimensionality of a javascript array
问题描述
编写包含数组并返回该数组的多维度的函数的最有效和/或最易读的方式是什么。现在可以假定数组仅包含基本类型。
What is the most efficient and/or most readable way to write a function that takes in an array and returns the degree of multi-dimensionality of that array. For now it can be assumed that the arrays only contain primitive types.
示例。
var arr = [[1,2],[3,4],[5,6]]
function findDim(a){
//logic goes here
}
findDim(arr); // returns 2
推荐答案
使用递归和 < a href = https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray rel = nofollow> Array.isArray
方法来检查元素是否为数组。
Use recursion and Array.isArray
method to check element is an array.
var arr = [
[1, 2],
[3, 4],
[5, 6]
];
function findD(arr) {
// check the element is an array then do
// recursion to check it's element
if (Array.isArray(arr)) {
return 1 + findD(arr[0]);
}
// else return `0` since it's not
// a nested array
return 0;
}
console.log(findD(arr));
仅供参考:对于较旧的浏览器,请检查 Array.isArray
方法的polyfill选项。
FYI : For older browser check polyfill option of Array.isArray
method.
UPDATE:如果它包含不同维数组,而您想获取更深的维度,然后使用 Array#map
和 Math.max
方法。
UPDATE : Incase it contains different dimensioned array and you want to get the deeper dimension then use Array#map
and Math.max
methods.
var arr = [
[1, 2],
[3, 4],
[5, [6]]
];
function findD(arr) {
// return 0 if not array else return the max value
// by finding all elements dimension
return Array.isArray(arr) ?
// generate the dimension value array
1 + Math.max.apply(Math, arr.map(findD)) : 0;
}
console.log(findD(arr));
或使用 Array#reduce
方法以获取最大值。
Or with Array#reduce
method to get the max value.
var arr = [
[1, 2],
[3, [4,[[3]]]],
[5, [6]]
];
function findD(arr) {
// return 0 if not array else return the max value
// by finding all elements dimension
return Array.isArray(arr) ? 1 + arr.reduce(function(a, b) {
// get the largest by comparing all the adjuscent
// elements dimension
return Math.max(a, findD(b));
}, 0) : 0;
}
console.log(findD(arr));
这篇关于查找JavaScript数组的维数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!