我试图将数组中的每个元素相互比较并输出结果。使用嵌套 for 循环,这本身就很简单。
a = [1, 2, 3, 4, 5];
for(let i = 0; i < a.length; i++) {
for(let k = i + 1; k < a.length; k++) {
console.log(a[i] + ' -> ' + a[k]);
}
}
对于这个输出将是
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
但我希望这些是随机的,例如类似
1 -> 2
2 -> 5
3 -> 4
等等
我该如何去做呢?
最佳答案
您可以创建一个函数来选择一个随机元素,切出该元素,然后选择另一个随机元素:
const arr = [1, 2, 3, 4, 5];
const randomElementsFromArr = () => {
const randIndex = Math.floor(Math.random() * arr.length);
const oneElement = arr[randIndex];
const slicedArr = [...arr.slice(0, randIndex), ...arr.slice(randIndex + 1)];
const anotherElement = slicedArr[Math.floor(Math.random() * slicedArr.length)];
return [oneElement, anotherElement];
};
console.log(randomElementsFromArr().join(' -> '));
关于javascript - 随机比较数组中的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50243746/