简体   繁体   English

Javascript 2D数组生成未按预期工作

[英]Javascript 2D array generation doesn't work as intended

I am new here, and to programming as well. 我在这里是新手,对于编程也是如此。 Anyway, to get in topic I wrote the following program with the purpose of generating a 2 dimensional array in JavaScript, and then displaying its elements in a table. 无论如何,为了进入主题,我编写了以下程序,目的是在JavaScript中生成二维数组,然后在表中显示其元素。 However, in the place where the value of the i row array index was supposed to show (like 1 in first row, then 2 in the second row, etc), the number 10 shows instead. 然而,在其中的值的地方i行数组索引应该显示(如1中第一行,然后2在第二行中,等等),数字10示出了代替。 So, I'd appreciate if someone could explain what I did wrong. 因此,如果有人可以解释我做错了,我将不胜感激。 Here is the code: 这是代码:

<table border="1">
    <script>
        var array1 = [];
        var array2 = [];
        for (var i = 0; i < 10; i++) {
            for (var j = 0; j < 10; j++) {
                array2[j] = (i + 1) + "-" + (j + 1);
            }
            array1[i] = array2;
        }

        for (var i = 0; i < 10; i++) {
            document.write("<tr>");
            for (var j = 0; j < 10; j++) {
                document.write("<td>" + array1[i][j] + "</td>");
            }
            document.write("</tr>");
        }
    </script>
</table>

You are adding the same array to array1 , again and again. 您一次又一次将相同的数组添加到array1 Instead you need to create new arrays every time. 相反,您每次都需要创建新的数组。

var array1 = [];

for (var i = 0; i < 10; i++ ) {
    var array2 = [];
    for (var j = 0; j < 10; j++) {
        array2[j] = (i+1) + "-" + (j+1);
    }
    array1[i]=array2;
}

But normally, this will be done with Array.prototype.push method, like this 但是通常,这将通过Array.prototype.push方法完成,就像这样

var array1 = [];

for (var i = 0; i < 10; i++ ) {
    var array2 = [];
    for (var j = 0; j < 10; j++) {
        array2.push((i+1) + "-" + (j+1));
    }
    array1.push(array2);
}

You can create new array each time after assigned array2 to array1 , something like this 您可以在将array2分配给array1之后每次创建新数组,类似这样

array2=[];

on

for (var i = 0; i < 10; i++ ) {
    for (var j = 0; j < 10; j++) {
        array2[j] = (i+1) + "-" + (j+1);

    }
    array1[i]=array2;
    array2=[]; //created new array each time after array2 assigned
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM