javascript 创建具有特定长度和宽度的二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13808325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:50:06  来源:igfitidea点击:

Creating a 2D array with specific length and width

javascriptarrays

提问by lawx

*see the title. I basically need it to create a blank array that can be any dimension like 40x60. Basically maybe something like makeArray(3, 4)makes an array like:

*见标题。我基本上需要它来创建一个空白数组,该数组可以是任何尺寸,例如 40x60。基本上可能类似于这样makeArray(3, 4)的数组:

[][][]
[][][]
[][][]
[][][]

回答by Kyle

Javascript arrays are dynamic in size. However, if you wish to create an array of a specific size, the Arrayconstructor takes an optional length argument:

Javascript 数组的大小是动态的。然而,如果你想创建一个特定大小的数组,Array构造函数需要一个可选的长度参数:

function makeArray(d1, d2) {
    var arr = new Array(d1), i, l;
    for(i = 0, l = d2; i < l; i++) {
        arr[i] = new Array(d1);
    }
    return arr;
}

Slightly shorter:

稍微短一点:

function makeArray(d1, d2) {
    var arr = [];
    for(let i = 0; i < d2; i++) {
        arr.push(new Array(d1));
    }
    return arr;
}

UPDATE

更新

function makeArray(w, h, val) {
    var arr = [];
    for(let i = 0; i < h; i++) {
        arr[i] = [];
        for(let j = 0; j < w; j++) {
            arr[i][j] = val;
        }
    }
    return arr;
}

回答by Moritz Roessler

Well make Array would be a simple function like this

那么 make Array 将是一个像这样的简单函数

    ?function makeArray(a,b) {
        var arr = new Array(a)
        for(var i = 0;i<a;i++)
            arr[i] = new Array(b)
        return arr
    }
    console.log(makeArray(4,4))

? But you don't have to define Arrays with functions you can simply do something like

? 但是你不必用函数定义数组,你可以简单地做一些类似的事情

var arr=[]
arr[10] = 10

Which would result in a Array with 10 Elements, 0 - 9 are undefined

这将导致具有 10 个元素的数组,0 - 9 是 undefined

But thats enough of an Answer in this case, i tried to point some things out in this question regarding Arrays, if you're interested you can take a look at this question

但在这种情况下,这已经足够了,我试图在这个问题中指出一些关于数组的事情,如果你有兴趣,你可以看看这个问题