简体   繁体   English

如何使用 Javascript 从随机生成的数字数组中省略 0?

[英]How to omit 0 from array of randomly generated numbers using Javascript?

I have done a code where it will generate 7 random numbers from 0 to 49.我已经完成了一个代码,它将生成从 0 到 49 的 7 个随机数。

HTML HTML

<button id="btn_generate" onClick="getMyLuckyNumbers()">GENERATE NUMBERS</button>
<div id="display"></div>

JS JS

function getMyLuckyNumbers() {
for (var allNumbers=[],i=0;i<50;++i) allNumbers[i]=i;

function shuffle(array) {
  var tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}

allNumbers = shuffle(allNumbers);

var luckyNumbers = "";
var g;

for (g = 0; g < 7; g++) {
    luckyNumbers += allNumbers[g] + "<br>";
}
document.getElementById("display").innerHTML = luckyNumbers;
}

I would like to know how I can omit 0?我想知道如何省略 0?

I attempted two ways, but both failed.我尝试了两种方法,但都失败了。

Attempt 1:尝试1:

Changed the i=0 to i=1 .i=0更改为i=1

for (var allNumbers=[],i=1;i<50;++i) 
  allNumbers[i]=i;

This did omit 0 but when 0 was randomly supposed to appear, it shows as undefined.这确实省略了 0,但是当 0 应该随机出现时,它显示为未定义。

Attempt 2:尝试2:

I tried to do an if statement.我试图做一个 if 语句。

if(allNumbers != 0) {
  allNumbers = shuffle(allNumbers);
}

But this still displays 0 if it happens to be randomly generated.但是如果它碰巧是随机生成的,它仍然显示 0。

So, how do I omit 0?那么,如何省略 0 呢?

The issue with starting i from 1 is that the 0 th index will be empty, and so when accessed gives undefined .1开始i的问题是第0 th索引将为空,因此访问时会给出undefined

So, if you want to avoid the number 0 , you can make i start at 1, but you would need to change the way you add numbers to your array.因此,如果您想避免数字0 ,您可以让i从 1 开始,但您需要更改将数字添加到数组的方式。 Instead of adding your numbers to your array by placing them at a specific index, you can .push() them to the end of your array each iteration like so:无需通过将数字放在特定索引处将它们添加到数组中,您可以将它们.push()到每次迭代的数组末尾,如下所示:

//                      \/------ start at i = 1, the 1st number to be added to your array
for (var allNumbers=[],i=1;i<50;++i) 
  allNumbers.push(i);

This way, you will fill up your array with numbers from 1 to 49 which can them be shuffled.这样,您将用149的数字填充您的数组,这些数字可以被打乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM