[英]How can i make 2 different shuffled arrays from an initial array? javascript
How can i make 2 different shuffled arrays from an initial array in javascript?如何从 javascript 中的初始数组制作 2 个不同的改组 arrays?
When i execute my code the 2 shuffled arrays are always the same.当我执行我的代码时,2 shuffled arrays 总是相同的。 I want my initial array to be unchangeable and the 2 new arrays to be differently shuffled.我希望我的初始数组是不可更改的,并且 2 个新的 arrays 进行不同的洗牌。
Thank you!谢谢!
const array = [
{
name: "Nick",
age: 15,
grade: 18
},
{
name: "John",
age: 16,
grade: 15
},
{
name: "Patrick",
age: 13,
grade: 11
},
{
name: "George",
age: 15,
grade: 19
}
];
console.log(array);
function shuffle(array) {
let currentIndex = array.length, randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
let array1 = shuffle(array);
console.log(array1);
let array2 = shuffle(array);
console.log(array2);
All you have to do is add the .slice
:您所要做的就是添加.slice
:
let array1 = shuffle(array.slice());
console.log(array1);
let array2 = shuffle(array.slice());
console.log(array2);
The .slice
means that you create a "copy" of the original array rather than modifying the existing array. .slice
意味着您创建原始数组的“副本”,而不是修改现有数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.