生成具有随机唯一值的数组

发布于 2025-02-10 10:46:00 字数 582 浏览 2 评论 0原文

我正在尝试使用循环在数组中的每个值中生成一个数组。具体来说,我想在数组中有五个元素,每个元素是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮光之海 2025-02-17 10:46:00

以下片段应产生您想要的行为。

// Fill an array with the numbers 1-100.
let randomizedArray = []
for (let i = 0; i < 100; i++) {
  randomizedArray.push(i + 1)
}

// Shuffle the array using a Fisher-Yates shuffle.
let m = randomizedArray.length,
  t, r;
while (m) {
  r = Math.floor(Math.random() * m--);
  t = randomizedArray[m];
  randomizedArray[m] = randomizedArray[r];
  randomizedArray[r] = t;
}

// Pop the first 5 elements of the shuffled array into a new array and print it.
let myArray = []
for (let i = 0; i < 5; i++) {
  myArray.push(randomizedArray.pop())
}
console.log(myArray)

有关改组阵列的更多信息,请参见此stackoverflow问题

The following snippet should produce the behaviour you want.

// Fill an array with the numbers 1-100.
let randomizedArray = []
for (let i = 0; i < 100; i++) {
  randomizedArray.push(i + 1)
}

// Shuffle the array using a Fisher-Yates shuffle.
let m = randomizedArray.length,
  t, r;
while (m) {
  r = Math.floor(Math.random() * m--);
  t = randomizedArray[m];
  randomizedArray[m] = randomizedArray[r];
  randomizedArray[r] = t;
}

// Pop the first 5 elements of the shuffled array into a new array and print it.
let myArray = []
for (let i = 0; i < 5; i++) {
  myArray.push(randomizedArray.pop())
}
console.log(myArray)

For more information on shuffling arrays, see this StackOverflow question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文