简体   繁体   English

如何从初始数组中制作 2 个不同的改组 arrays? javascript

[英]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.

相关问题 如何在Javascript中创建自定义对象数组的数组? - How can I make an array of arrays of custom objects in Javascript? 如何在 myArray 的 Javascript 中创建一个包含嵌套数组的数组? - How can I make an array instaed of nested arrays in Javascript from myArray? 我如何通过从 16 个数字的洗牌数组中弹出一个数字并将其插入 HTML 来构建表格? - how can i build table by poping a number from shuffled array of 16 numbers and insert it into the HTML? 如何从javascript对象制作数组数组? - How to make an array of arrays from a javascript object? 如何将 arrays 数组从字符串转换为 Javascript 中的数字? - How can i turn an array of arrays from strings to numbers in Javascript? 将多个随机排列的数组连接到JavaScript中的一个大随机数组中 - Concat multiple shuffled arrays into one big random array in javascript 如何在javascript中的新数组中使用相同的appName从两个不同的数组中推送元素 - how to make push elements from two different arrays with same appName inside a new Array in javascript Javascript 如何将新元素从初始数组推送到同一索引的 arrays 数组中的每个数组? - Javascript how to push a new element from an initial array to each array inside an array of arrays at the same index? 如何在 JavaScript 中解构数组数组? - How can I destructure an array of arrays in JavaScript? Javascript 重组乱序数组 - Javascript Reorganizing Shuffled Array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM