如何获取多维Javascript数组的维度?

And*_*een 4 javascript arrays

通常,在某些情况下我需要确定Javascript数组是否为矩形(并获取数组的尺寸).在这种情况下,我的意思是确定数组的每个元素是否是具有相同长度的数组.我怎样才能做到这一点?

function getArrayDimensions(theArray){
    //if the array's dimensions are 3x3, return [3, 3], and do the same for arrays of any dimension
    //if the array is not rectangular, return false
}
Run Code Online (Sandbox Code Playgroud)

另外,如何将此函数推广到多维数组(2x5x7,3x7x8x8等)?

Ja͢*_*͢ck 9

此递归函数返回给定数组的所有维度,如果一个或多个维度不是直的(即数组项目之间的大小不同),则返回false.它使用辅助函数来确定两个简单数组是否相同(在使用它之前阅读函数注释).

// pre: a !== b, each item is a scalar
function array_equals(a, b)
{
  return a.length === b.length && a.every(function(value, index) {
    return value === b[index];
  });
};

function getdim(arr)
{
  if (/*!(arr instanceof Array) || */!arr.length) {
    return []; // current array has no dimension
  }
  var dim = arr.reduce(function(result, current) {
    // check each element of arr against the first element
    // to make sure it has the same dimensions
    return array_equals(result, getdim(current)) ? result : false;
  }, getdim(arr[0]));

  // dim is either false or an array
  return dim && [arr.length].concat(dim);
}

console.log(getdim(123)); // []
console.log(getdim([1])); // [1]
console.log(getdim([1, 2])); // [2]
console.log(getdim([1, [2]])); // false
console.log(getdim([[1, 2], [3]])); // false
console.log(getdim([[1, 2],[1, 2]])); // [2, 2]
console.log(getdim([[1, 2],[1, 2],[1, 2]])); // [3, 2]

console.log(getdim([[[1, 2, 3],[1, 2, 4]],[[2, 1, 3],[4, 4, 6]]])); // [2, 2, 3]

console.log(getdim([[[1, 2, 3], [1, 2, 4]], [[2, 1], [4, 4]]])); // false
Run Code Online (Sandbox Code Playgroud)