我正在使用下面的代碼生成0到Totalfriends之間的隨機數,我想要得到隨機數,但不應該重複。任何想法如何?如何生成沒有重複的隨機數字javascript
這是我在範圍使用
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;
});
});
你應該使用'Math.floor(Math.random()* totalFriends)',否則你有時會超過數組的末尾 – Eric