简体   繁体   中英

Javascript: Problem adding array into 2D array

I am trying to shuffle an array and add the shuffled-set every time into 2D array using a loop. the problem is that the resulted 2D array contains the same shuffled-set for all rows, while the output of each shuffled-set is different.

So; what do I miss here?

var b=[1,2,3,4,5,6,7,8,9];
var matrix=[];

for(var i=0; i <5; i ++){
    shuffle(b);
    matrix[i]=b;
    //matrix.push(b);
    console.log(b);
}
console.log(matrix);


function shuffle(array) {
    var ctr = array.length, temp, index;
    while (ctr > 0) {
        index = Math.floor(Math.random() * ctr);
        ctr--;
        temp = array[ctr];
        array[ctr] = array[index];
        array[index] = temp;
    }
    return array;
}

the output:

Array(9) [ 7, 3, 4, 9, 2, 1, 6, 8, 5 ]
Array(9) [ 5, 6, 3, 9, 8, 4, 1, 7, 2 ]
Array(9) [ 9, 5, 2, 4, 3, 6, 8, 7, 1 ]
Array(9) [ 3, 5, 2, 1, 4, 9, 6, 8, 7 ]
Array(9) [ 5, 9, 4, 6, 7, 3, 2, 8, 1 ]

(5) […]
0: Array(9) [ 5, 9, 4, … ]
1: Array(9) [ 5, 9, 4, … ]
2: Array(9) [ 5, 9, 4, … ]
3: Array(9) [ 5, 9, 4, … ]
4: Array(9) [ 5, 9, 4, … ]
length: 5

You only have one 1D array object, ie b . And you keep shuffling and adding that same object reference to matrix :

 matrix[i]=b;

So even after you have added such a row, you will keep mutating that added row when you call shuffle again.

You should take a copy of the array so you have different arrays that get added to matrix :

 matrix[i]=b.slice();

There are several ways to get a copy: b.slice() can also be Array.from(b) , or [...b] .

Alternatively, you could put the initalisation of b as new array, inside the loop:

var matrix = [];
for (var i = 0; i < 5; i++){
    var b = [1,2,3,4,5,6,7,8,9];
    shuffle(b);
    matrix[i] = b;
}

As you have designed shuffle to return the array also, you can reduce the above code to:

var matrix = [];
for(var i = 0; i < 5; i++){
    matrix[i] = shuffle([1,2,3,4,5,6,7,8,9]);
}

you could take a shallow clone of your shuffle.

 for(var i=0; i <5; i ++){
    const clone = {...shuffle(b)};
    matrix[i]=clone;
    //matrix.push(b);
    console.log(clone);
}
console.log(matrix);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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