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


- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01