closure in for-loop > different tries failed

2019-03-06 20:14发布

I want to create a 2-dimensional array with an index-number in each first element.

EDIT:

thx a lot so far..

@carl: I did so much function creation just to show the kind of tries I did..

jonhopkins idea gave rise to this:

this works:

$('#create_indexed_array').click(function() {

    var new_array = [[9,9],[9,9],[9,9],[9,9],[9,9]];

    for (var i = 0; i < 5; i++) {

        new_array[i][0] = i;

    }

    alert(JSON.stringify(new_array));

});

BUT this works not:

$('#create_indexed_array').click(function() {


    var new_array = new Array(new Array());

    for (var i = 0; i < 2; i++) {
        new_array[0][i] = ""; // create cols
    } 

    for (var i = 1; i < 5; i++) {
        new_array[i] = new_array[0]; // create rows
    }

    for (var i = 0; i < 5; i++) {
        new_array[i][0] = i; // set index

    }

    alert(JSON.stringify(new_array));

});

2条回答
三岁会撩人
2楼-- · 2019-03-06 21:02

try do this

for (var i = 0; i < $('#rows').val(); i++) {
    new_array[i][0] = i;
}

The definitions of 'i' can be done in the beginning of the main function, because the for loop has not closure. So, when the loop ends the 'i' var is still available. you can read this book http://shop.oreilly.com/product/9780596517748.do

查看更多
时光不老,我们不散
3楼-- · 2019-03-06 21:04

There are no two-dimensional arrays in JavaScript, there are just array objects that may contain other array objects (but also anything else). new Array(new Array()); does not what you expect. Btw, you might use an empty-array-literal [] instead of calling the constructor explicitly.

var new_array = [];
for (var i=0; i<5; i++) {
    // create and add a new subarray explicitly:
    new_array[i] = [];
    // add a value to that subarray:
    new_array[i][0] = i;
    // add other values to the subarray:
    new_array[i][1] = "";
}
// new_array now looks like this:
[[0, ""], [1, ""], [2, ""], [3, ""], [4, ""]]

// You might shorten the whole code by using stuffed literals for the sub arrays:
for (var new_array=[], i=0; i<5; i++)
    new_array[i] = [i, ""];
查看更多
登录 后发表回答