[英]Array item gets the value “undefined”
I am trying to create an array of unique numbers from 0 to 10:我正在尝试创建一个从 0 到 10 的唯一数字数组:
var numbers=[];
var i=0;
var prevLength=numbers.length;
while(numbers.length<10){
prevLength=numbers.length;
if(numbers.length<=prevLength){
numbers[i]=Math.floor(Math.random()*10);
numbers=[...new Set(numbers)];
console.log(numbers);
i++;
}
}
But the output of the array will always have an undefined item at a random index which I don't know why.但是数组的 output 在随机索引处总是有一个未定义的项目,我不知道为什么。
[ 9, 1, 8, 7, undefined, 5, 2, 0, 6, 3 ]
Can somebody help me out?有人可以帮帮我吗?
This happens because of this statement:发生这种情况是因为以下声明:
numbers=[...new Set(numbers)];
This can potentially reduce the length of numbers
, but as you don't align the value of i
with the potential shortening, you'll get gaps.这可能会减少
numbers
的长度,但由于您没有将i
的值与潜在的缩短对齐,您会得到差距。
The solution is to drop the use of numbers[i] =
and use numbers.push
instead:解决方案是放弃使用
numbers[i] =
并改用numbers.push
:
numbers.push(Math.floor(Math.random()*10));
If the new Set
removes a duplicate, then i
will be larger than the length of numbers, due to numbers.length
shrinking but i
still getting increased.如果
new Set
删除了重复项,则i
将大于数字的长度,因为numbers.length
缩小但i
仍然增加。 Don't keep track of an index, just use .push
to push to the end of the array:不要跟踪索引,只需使用
.push
推送到数组的末尾:
var numbers=[];
var prevLength=numbers.length;
while(numbers.length<10){
numbers.push(Math.floor(Math.random()*10));
numbers=[...new Set(numbers)];
console.log(numbers);
}
A more efficient way to make use of the Set would be something like:使用 Set 的一种更有效的方法是:
const set = new Set() while(set.size < 10){ const rand = Math.floor(Math.random()*10); .set.has(rand) && set;add(rand). } const res = [...set] console.log(res)
You can also do this without Set
您也可以在没有
Set
的情况下执行此操作
eg:例如:
var numbers = [];
var rand;
while(numbers.length < 10){
rand = Math.floor(Math.random()*10);
numbers.indexOf(rand) === -1 && numbers[numbers.length] = rand;
}
console.log(numbers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.