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

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

失去邏輯!javaScript中的隨機唯一數字

失去邏輯!javaScript中的隨機唯一數字

至尊寶的傳說 2022-12-02 10:38:59
我需要編寫一個函數來生成 0 到 60 之間的 6 個隨機數,然后將它們存儲在給定的數組中。此外,此函數無法在返回的數組中存儲重復項。好吧,我在 StackOverflow 上找到了一個非常有用的答案(感謝 Shouvik),我將在下面展示。但這是我擁有大部分邏輯但錯過了兩個核心要素的東西我試圖在沒有第二個臨時數組的情況下執行此操作我不知道如何在數組中找到重復項我知道我必須 .indexOF 數組 我知道我必須 .push 一個新值到數組這是我在找到解決方案之前的代碼:function gerarDezenas() {  let jogo = [];  for (var i = 0;i < 6;i++) {    jogo.push(Math.round(Math.random()*(1 , 60)+1));    if (jogo.indexOf(jogo) == //clueless)c{         .push() // ?? clueless either    }  }  return jogo}console.log(gerarDezenas())所以我發現我需要另一個數組和 if 條件來比較它function gerarDezenas() {  let jogo = [];   for (var i = 0; i < 6; i++) {    var temp = Math.round(Math.random()*(1 , 60)+1);    if (jogo.indexOf(temp) == -1) {        jogo.push(temp)    }    else {        i--;    }  }  return jogo}該代碼現在可以按預期工作,但我并不真正理解它并且這里的問題!我不知道這些行在做什么:if (jogo.indexOf(temp) == -1) {    jogo.push(temp)}else {      i--;}有人可以向我澄清 if 和 else 在做什么嗎?如果您閱讀了帖子,非常感謝!附圖請不要恨我
查看完整描述

3 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

/*Check whether array named jogo has the temp element inside it, if not add the temp element to jogo. */

if (jogo.indexOf(temp) == -1){

    jogo.push(temp)

    }


/*When you are inside this if else block the i's value must have been increased, now if

temp is not being inserted because it's already there in the array, decrement i so that the if else block again runs with the same I what it was earlier before increment.

*/

    else {

      i--;

    }


查看完整回答
反對 回復 2022-12-02
?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

此代碼循環遍歷整個數組以檢查隨機數是否在數組內。但如果不是,它將輸出 -1 表示當前隨機數沒有重復

if (jogo.indexOf(temp) == -1)

雖然此代碼只是反轉循環,因此它取消了 i++。

i--;


查看完整回答
反對 回復 2022-12-02
?
烙印99

TA貢獻1829條經驗 獲得超13個贊

如果 temp(隨機數)不在 jogo 數組中(如果找不到值,indexOf 總是返回 -1)


if (jogo.indexOf(temp) == -1)

const arr = ["A","B","C"];

console.log(arr.indexOf("D"));

console.log(arr.indexOf("C"));


然后將其添加到數組中


jogo.push(temp)

否則重做循環,希望得到一個不在 jogo 數組中的數字(-- 會抵消 ++ )


 i--;

let i = 5;

i--

i++

console.log(i);


查看完整回答
反對 回復 2022-12-02
  • 3 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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