我有一个字符串数组。
let people = ['Bill', 'Paul', 'William', 'Francis'];
我想创建随机对:
Bill -> Paul
Paul -> Francis
William -> Bill
Francis -> William
所有情侣必须是唯一的,第二列中的每个名字只能使用一次。
这是我的代码,但它没有按预期工作。
let receivers = people.sort(function() { return 0.5 - Math.random() });
for (let i in people)
{
console.log(people[i] +' -> '+ receivers[i]);
}
有什么建议吗?
最佳答案
从How to randomize (shuffle) a JavaScript array?:中获取随机数组并将它与下一个元素像一个圆一样分割
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
let people = ['Bill', 'Paul', 'William', 'Francis'];
shuffle(people);
for(var i=0;i<people.length;i++){
console.log(people[i]+" -> "+people[(i+1<people.length)?i+1:0]);
}
关于javascript - 将数组条目加入唯一关系 (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40978531/