Javascript 获取数组中维度的大小

Javascript 获取数组中维度的大小,javascript,multidimensional-array,Javascript,Multidimensional Array,如何获得给定多维数组的维度? 编辑:可以是1维、2维或3维,但每个子数组的长度相同 i、 e.为了 var a = [[1,1,1], [1,1,1]] 将是[2,3] var dim = [ a.length, a[0].length ]; 考虑到每个子数组的长度相同,这应该是可行的,但是,如果不是这样,您可能需要执行以下操作: function findDim(a){ var mainLen = 0; var subLen = 0; mainLe

如何获得给定多维数组的维度?
编辑:可以是1维、2维或3维,但每个子数组的长度相同

i、 e.为了

var a = [[1,1,1], [1,1,1]]
将是[2,3]

var dim = [
    a.length,
    a[0].length
];
考虑到每个子数组的长度相同,这应该是可行的,但是,如果不是这样,您可能需要执行以下操作:

function findDim(a){
    var mainLen = 0;
    var subLen = 0;

    mainLen = a.length;

    for(var i=0; i < mainLen; i++){
        var len = a[i].length;
        subLen = (len > subLen ? len : subLen);
    }

    return [mainLen, subLen];
};
函数findDim(a){
var mainLen=0;
var-n=0;
mainLen=a.长度;
对于(变量i=0;i转租?len:转租);
}
返回[mainLen,subLen];
};
如果您知道内部数组的
长度
不会改变,那么这是可行的


如果内部数组的维度不是静态的,则可以组合和来计算最大维度:

const dimensions = [
    arr.length,
    arr.reduce((x, y) => Math.max(x, y.length), 0)
];
或者,如果要将长度放入
a

var a = [[1,1,1], [1,1,1]];
for(i in a) a[i]=a[i].length;
编辑: 很抱歉,我不在这门课上。下面的代码计算二维数组的最大行和最大列

var innerSize = 0, i=0, l=a.length, l2;
for(;i<l;i++) if(innerSize<(l2=a[i].length)) innerSize = l2
[l, innerSize]
var innerSize=0,i=0,l=a.length,l2;

对于(;i考虑到子列表可以有不同的大小,获取最小大小或根据需要使其最大

function size(ar){
    var row_count = ar.length;
    var row_sizes = []
    for(var i=0;i<row_count;i++){
        row_sizes.push(ar[i].length)
    }
    return [row_count, Math.min.apply(null, row_sizes)]
}
size([[1, 1, 1], [1, 1, 1]])

这适用于任何维度(假设每个子数组具有相同的长度):


此函数将检查数组是否有效(不是标量或字符串),以及该数组的元素是否有效(它们具有相同的长度),然后在满足所有条件时给出维度,否则抛出错误


function getDim(x){
    dim=[]
    try {
        // throw error if the passed variable is a string or a scalar
        if((isFinite(x) && !x.length) || typeof(x)=='string') throw  'This is a scalar or a string  not an array!';
        // loop over the array to extract length of each element.
        // if we get an element that is not an array, return the found dimensions 
        while (x){

            dim.push(x.length)
            currentLevel=x
            x=Array.isArray(x[0])?x[0]:false;
            // check if all elements of the array are of equal dimention. If not, throw an error
            ans=currentLevel.every((value,index,arr)=>{ return value.length==x.length}) ;
            if(!ans) throw 'elements of the array are not of equal dimension !'

        }
        return dim
    } catch (error) {
        return error 
    }
}


此外,您还可以使用递归函数计算数组的形状,假设所有维度都相同:

arrayShapeRecursive = arr => {
  return arr.length ? [...[arr.length], ...arrayShapeRecursive(arr[0])] : [];
}

在您的情况下,只需使用
arr.length
arr[0].length
即可找到宽度和深度

通常,数组的深度是可变的,因此有必要使用递归遍历整个数组

我创建了一个
Object
原型方法
来确定数组的深度。要使用它,只需调用
myArray.dimensionsDeep()
。它既适用于
对象
也适用于
数组

Object.prototype.isMultidimensional = function()
{
    return this.constructor.name !== "String" && Object.keys(this).some((i) => { return this[i].length > 0; });
}

Object.prototype.dimensionsDeep = function()
{
    if (typeof Object.dimensions === 'undefined')
    {
        if (!this.length)
            return 0;
        Object.dimensions = 0;
        Object.currentLevel = 0;
    }
    Object.keys(this).forEach((i) =>
    {
        if (this[i].isMultidimensional())
        {
            Object.currentLevel++;
            if (Object.currentLevel > Object.dimensions)
                Object.dimensions = Object.currentLevel;
            this[i].dimensionsDeep();
        }
    });
    Object.currentLevel--;
    if (Object.currentLevel < 0)
    {
        delete(Object.currentLevel);
        var temp = Object.dimensions;
        delete(Object.dimensions);
        return temp + 1;
    }
}
Object.prototype.isMultidimensional=函数()
{
返回this.constructor.name!==“String”&&Object.keys(this).some((i)=>{返回this[i].length>0;});
}
Object.prototype.dimensionsDeep=函数()
{
if(type of Object.dimensions==‘未定义’)
{
如果(!this.length)
返回0;
Object.dimensions=0;
Object.currentLevel=0;
}
Object.keys(this.forEach)((i)=>
{
if(此[i].isMultidimensional())
{
Object.currentLevel++;
if(Object.currentLevel>Object.dimensions)
Object.dimensions=Object.currentLevel;
此[i].dimensionsDeep();
}
});
Object.currentLevel--;
如果(Object.currentLevel<0)
{
删除(Object.currentLevel);
var temp=对象。维度;
删除(对象.尺寸);
返回温度+1;
}
}

获取多维数组的元素数就这么简单

var Size = a.join(',').split(',').length;

什么是子列表大小不同?到目前为止,这是我找到的最好的答案:自从
.reduce()
被添加到数组原型中以来,对于固定的内部长度(
const-dimensions=[a.length,a[0].length]
)以及不均匀的长度(
const-dimensions=[a.length,a.reduce((t,e))来说,这都是一条直线=>Math.max(t,e.length),0)]
)。对于大小稳定的输入,后者产生与第一个相同的答案。
“[”[“+arr.length+”,“+arr[0]。length+”]”
:)函数arrySize(arr){返回{c:arr.length,r:arr[0]。length==未定义的?1:arr[0]。length};}或者,对于不均匀的内部尺寸:
尺寸=[a.length,a.reduce((t,e)=>数学最大值(t,e.长度),0)]
这适用于任何维度的数组,还是仅适用于二维数组?@AndersonGreen它仅适用于二维数组,但递归调用应使其适用于N维数组。试着详细说明为什么你的解决方案有效。

function getDim(x){
    dim=[]
    try {
        // throw error if the passed variable is a string or a scalar
        if((isFinite(x) && !x.length) || typeof(x)=='string') throw  'This is a scalar or a string  not an array!';
        // loop over the array to extract length of each element.
        // if we get an element that is not an array, return the found dimensions 
        while (x){

            dim.push(x.length)
            currentLevel=x
            x=Array.isArray(x[0])?x[0]:false;
            // check if all elements of the array are of equal dimention. If not, throw an error
            ans=currentLevel.every((value,index,arr)=>{ return value.length==x.length}) ;
            if(!ans) throw 'elements of the array are not of equal dimension !'

        }
        return dim
    } catch (error) {
        return error 
    }
}

arrayShapeRecursive = arr => {
  return arr.length ? [...[arr.length], ...arrayShapeRecursive(arr[0])] : [];
}
Object.prototype.isMultidimensional = function()
{
    return this.constructor.name !== "String" && Object.keys(this).some((i) => { return this[i].length > 0; });
}

Object.prototype.dimensionsDeep = function()
{
    if (typeof Object.dimensions === 'undefined')
    {
        if (!this.length)
            return 0;
        Object.dimensions = 0;
        Object.currentLevel = 0;
    }
    Object.keys(this).forEach((i) =>
    {
        if (this[i].isMultidimensional())
        {
            Object.currentLevel++;
            if (Object.currentLevel > Object.dimensions)
                Object.dimensions = Object.currentLevel;
            this[i].dimensionsDeep();
        }
    });
    Object.currentLevel--;
    if (Object.currentLevel < 0)
    {
        delete(Object.currentLevel);
        var temp = Object.dimensions;
        delete(Object.dimensions);
        return temp + 1;
    }
}
var Size = a.join(',').split(',').length;