How to generate random numbers with no repeat javascript(如何生成不重复的随机数 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);
这篇关于如何生成不重复的随机数 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何生成不重复的随机数 javascript


基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01