如何生成不重复的随机数 javascript
我正在使用以下代码生成 0 到 Totalfriends 之间的随机数,我想获取随机数,但它们不应重复.知道怎么做吗?
I am using the following code which generates random number between 0 to Totalfriends, I would like to get the random numbers but they should not be repeated. Any idea how?
这是我正在使用的代码
FB.getLoginStatus(function(response) {
var profilePicsDiv = document.getElementById('profile_pics');
FB.api({ method: 'friends.get' }, function(result) {
// var result =resultF.data;
// console.log(result);
var user_ids="" ;
var totalFriends = result.length;
// console.log(totalFriends);
var numFriends = result ? Math.min(25, result.length) : 0;
// console.log(numFriends);
if (numFriends > 0) {
for (var i=0; i<numFriends; i++) {
var randNo = Math.floor(Math.random() * (totalFriends + 1))
user_ids+= (',' + result[randNo]);
console.log(user_ids);
}
}
profilePicsDiv.innerHTML = user_ids;
});
});
推荐答案
这是一个函数,它将从 array
中获取 n 个随机元素,并根据 Fisher-yates shuffle 返回它们.请注意,它将修改 array
参数.
Here's a function that will take n random elements from array
, and return them, based off a fisher-yates shuffle. Note that it will modify the array
argument.
function randomFrom(array, n) {
var at = 0;
var tmp, current, top = array.length;
if(top) while(--top && at++ < n) {
current = Math.floor(Math.random() * (top - 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array.slice(-n);
}
假设您的代码按照我的想法运行,那么您已经拥有一组用户 ID:
Assuming your code works how I think it does, you already have an array of userids:
var random10 = randomFrom(friendIds, 10);
相关文章