gpt4 book ai didi

javascript - 如何将数组 ABC 分配给另一个大小为 6 的数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:57:15 25 4
gpt4 key购买 nike

例如

array1 = [A,B,C]

array2 = []

有没有办法将A、B、C按随机顺序复制到array2,并且复制两次?

喜欢

array2 = [A,C,B,A,B,C]

最佳答案

您可以创建一个函数来对数组进行随机排序并返回一个新数组。

然后,您可以调用它两次,生成 2 个不同的数组,并使用 concat 将它们合二为一。

/*** Function declaration to make a random sort in an Array ***/
function randomSort(arr) {
var newArr = []; // create an empty array that will be returned
while (newArr.length < arr.length) { // until newArray is not fullfilled, keep the loop
var rndIdx = Math.floor(Math.random() * arr.length); // get a random index
// see if the new array already contains the element of that index
if (newArr.indexOf(arr[rndIdx]) === -1) {
newArr.push(arr[rndIdx]); // if not, put the element into the new array
}
}
return newArr; // return the new array fullfilled
}

/*** Usage ***/
var myArr = ['A', 'B', 'C'];
// sort the array twice and concat the results
var finalArr = randomSort(myArr).concat(randomSort(myArr));

document.querySelector('div').innerHTML = finalArr.toString();
console.log(finalArr);
<div></div>

关于javascript - 如何将数组 ABC 分配给另一个大小为 6 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com