-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

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 に答える