This question already has an answer here:
- Copying array by value in JavaScript 19 answers
var nums = [1,2,3,4,5];
function shuffle(array){
var newArr = Object.assign(array);
var counter = newArr.length;
while(counter > 0){
var index = Math.floor(Math.random() * counter);
counter--;
temp = newArr[counter];
newArr[counter] = newArr[index];
newArr[index] = temp;
}
return newArr;
}
shuffle(nums);
The newarray comes back shuffled but so does the original array. I thought by using object.assign that it would create a copy of the array and that the original array wouldn't be touched but used as a copy. What am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire