closure in for-loop > different tries failed

我与影子孤独终老i 提交于 2019-12-02 13:05:10

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

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, ""];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!