生成具有随机唯一值的数组
我正在尝试使用循环在数组中的每个值中生成一个数组。具体来说,我想在数组中有五个元素,每个元素是1到100之间的随机数(无重复)。
这是正确的方法吗?
PS我是一个只有8天的JS体验的初学者。
提前致谢!
let arr = []
let num = 0
let x = 4
while (x >= 0) {
if (arr.indexOf(arr[x]) == arr.lastIndexOf(arr[x])){
arr.push(Math.floor(Math.random(num)*100))
} else if (arr.indexOf(arr[x]) !== arr.lastIndexOf(arr[x])) {
arr.push(Math.floor(Math.random(num)*100))
} else {
arr.push(Math.floor(Math.random(num)*100))
}
x--
}
console.log(arr)
I am trying to generate an array using a loop with each value in the array being unique. Specifically, I would like to have five elements in the array, with each being a random number between 1 and 100 (without duplicates).
Is this the right way to do it?
P.S I am a beginner with only 8 days of JS experience.
Thanks in advance!
let arr = []
let num = 0
let x = 4
while (x >= 0) {
if (arr.indexOf(arr[x]) == arr.lastIndexOf(arr[x])){
arr.push(Math.floor(Math.random(num)*100))
} else if (arr.indexOf(arr[x]) !== arr.lastIndexOf(arr[x])) {
arr.push(Math.floor(Math.random(num)*100))
} else {
arr.push(Math.floor(Math.random(num)*100))
}
x--
}
console.log(arr)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下片段应产生您想要的行为。
有关改组阵列的更多信息,请参见此stackoverflow问题。
The following snippet should produce the behaviour you want.
For more information on shuffling arrays, see this StackOverflow question.