-7

这是示例代码。

window.onload = function() {
    var i, arr = [], result = [];

    arr.push(1);
    arr.push(2);
    arr.push(3);

    for ( i = 0; i < 20; i++ ) {
        arr.push(5);
        arr.push(6);

        result.push(arr);
        arr.length = 3;
    }

    console.log(result);
}

输出:

 Array[20] 

 0: Array[3] 

 1: Array[3] 

 2: Array[3]

 etc...
4

3 回答 3

4

您的数组数组包含对您将长度设置为 3 的数组的引用。这正是您应该得到的结果。链接到 ECMA 5.1。

于 2013-06-21T13:36:40.153 回答
2
window.onload = function() {
    //create ONE array arr and one array result
    var i, arr = [], result = [];

    //fill array with three values
    arr.push(1);
    arr.push(2);
    arr.push(3);


    for ( i = 0; i < 20; i++ ) {
        //fill array with two more values
        arr.push(5);
        arr.push(6);

        //add a reference to arr to result
        result.push(arr);

        //change the length of arr to 3 => delete the last two items
        arr.length = 3;
    }
    //----> this repeats twenty times. you add two items to arr, add a reference to arr 
    //to result and delete the two items again. but the references that are stored in     
    // result will always point to one and the same array arr. 

    //and that's what you get in the end: and array filled with 20 references to another 
    //array with three items in it.
    console.log(result);
}
于 2013-06-21T13:46:59.240 回答
0
result.push(arr);

当您调用上述内容时,您还没有将 arr 的内容推送到结果上;您已将 arr 本身推到结果上。

你的循环第一次运行时, arr 有 3 个元素,你再推 2 个元素;arr 现在有 5 个元素(1,2,3,5,6)。您将 arr 推到结果上 - arr 仍然有 5 个元素,而结果有 1 个元素是对 arr 的引用。

现在您将 arr 的长度设置为 3,因此 arr 有 3 个元素 (1,2,3)。result 仍然有一个元素,它仍然是对 arr 的引用。

除此之外,我不确定您的期望或您认为错误在哪里。如果你仍然认为有问题,你将不得不解释更多。

于 2013-06-21T13:50:29.350 回答