如何在 Javascript 中创建二维数组

How to create a 2D array in Javascript

我正在尝试使用 javascript 创建一个二维数组,我最终可以将其放入嵌套循环中以提取 X/Y 信息。

我做错了什么?


function createMatrix(){
    let colcount = 0;
    let rowcount = 0;

    var pixel_array = new Array();
    var y_array = new Array();

    for (var i = 0; i <= 100; i++){
        var checker = (i+1) % 10;
        if(checker == 0){
            y_array.push(i);
            //create new X array
            pixel_array[rowcount] = [];
            //push column data into row array
            pixel_array[rowcount].push(y_array);
            //create new Y array 
            var y_array = new Array();
            //increment row counter
            //reset column counter
            parseInt(rowcount++);
            colcount = 0;
        }else{
            y_array.push(i);
            parseInt(colcount++);
        }
    }

    //sanity check: spit out the matrix
    for (var x=0; x<10;x++){
        for(var y=0; y<10; y++){
            console.log(pixel_array[x][y]);
        }
    }

}

我期待调用特定的 X/Y 'coordinate' 并从 'cell' 中提取信息。但是,我收到一个错误,基本上说数组的 [Y] 部分未定义。

查看 console.log 和 console.table - 我可以看到 X 数组已填满,但这并不像我期望的那样,只是一个数字列表而不是另一个数组。

编辑:更具体地说,我的目标是从单个 For 循环创建一个二维数组。代码底部的嵌套 for 循环显示为我想如何调用 'cells' [X][Y].

的示例

此代码:

pixel_array[rowcount] = [];
//push column data into row array
pixel_array[rowcount].push(y_array);

创建一个新数组,将其存储在 pixel_array[rowcount] 中,然后将 y_array 压入其中。所以此时,您有一个数组 (pixel_array),其中一个条目是一个数组(您通过 [] 创建的那个),一个条目是一个数组 (y_array)。这比 2D 数组更接近 3D 数组。

您可能把它复杂化了一点。我不能完全弄清楚你想要你的最终数组是什么,所以这里有一个创建 3x4“2D 数组”的例子(它不是真正的¹,它是一个数组数组,但是......)数字 1 -12在里面,看评论:

// Create the outer array
var array = [];
for (var x = 0; x < 4; ++x) {
    // Create the inner array for this row and store it in `array[x]`
    var inner = array[x] = [];
    for (var y = 0; y < 3; ++y) {
        // Set the value of the inner array at `y`,
        // which is also `array[x][y]`
        inner[y] = (x * 3) + y + 1;
    }
}
console.log(array);
.as-console-wrapper {
    max-height: 100% !important;
}


您在评论中说:

I want to create a 2D array from a single For loop. So in my example I'm looping 0-99, with the expected result being a 10x10 'matrix' (0-9, 10-19, 20-29, etc).

这是一个例子:

// Create the outer array
var array = [];
var inner;
for (var n = 0; n < 100; ++n) {
    // Time to create a new inner array?
    if (n % 10 === 0) { // It's important that this condition is true on the first loop iteration
        inner = [];
        array.push(inner);
    }
    // Add this `n` to the current inner array
    inner.push(n);
}
console.log(array);
.as-console-wrapper {
    max-height: 100% !important;
}


¹ "it isn't really, it's an array of arrays" - JavaScript 没有多维数组。它具有可以包含其他数组的数组。对于许多用途,区别并不重要,但它意味着(除其他外)数组可以 锯齿状 :并非外部数组中的所有条目都必须具有相同的长度. (事实上​​ ,它们甚至不必是数组。)