亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何創建一個包含非重復數字的數組?

如何創建一個包含非重復數字的數組?

慕后森 2023-08-18 16:57:31
這是我的第一個問題。我需要生成一個包含 16 個隨機數的數組,這就是我的解決方案:var arr = [];for (var i = 0; i < 16; i++) {    arr.push(Math.floor(Math.random() * 100) + 1);}問題是這樣就有可能出現重復的數字。有人可以幫助我嗎?提前致謝。
查看完整描述

2 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

最短的方法是使用 aSet并檢查它的需求size。

let numbers = new Set,

? ? result;

? ??

while (numbers.size < 16) numbers.add(Math.floor(Math.random() * 100) + 1);



result = [...numbers];


console.log(...result);



查看完整回答
反對 回復 2023-08-18
?
慕容森

TA貢獻1853條經驗 獲得超18個贊

使用 while 循環


const MAX_NUMBER = 16;

const arr = [];


do {


  const randomNumber = Math.floor(Math.random() * 100) + 1

  

  // Push if the array does not contain it

  if (!arr.includes(randomNumber)) {

     arr.push(randomNumber);

  }


} while (arr.length < MAX_NUMBER);


console.log(arr)


查看完整回答
反對 回復 2023-08-18
  • 2 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號