简体   繁体   English

如何使用 for in 循环动态填充数组

[英]How to dynamically populate an array using a for in loop

To return an array set with a sequence of random numbers between 1 and 500 I tried to refactor a standard for loop for(var i = 0; i< 50; i++) and that worked but when I tried to do a refactor using a for in loop it doesn't.为了返回一个包含 1 到 500 之间的随机数序列的数组set ,我尝试重构标准 for 循环for(var i = 0; i< 50; i++)并且有效,但是当我尝试使用for in重构时for in循环中它没有。 My guess is that there is something about the array.length property and it's use that I'm screwing up.我的猜测是array.length属性有一些东西,它的用途是我搞砸了。

TL;DR Why does this return an array of 50 undefined elements rather than an array of 50 random integers? TL;DR为什么这会返回一个包含 50 个未定义元素的数组,而不是包含 50 个随机整数的数组? And is there a way to make this approach work?有没有办法让这种方法奏效?

var set = [];
set.length = 50;

for(var i in set){
    set[i] = Math.floor((Math.random() * 500) + 1);
}

console.log(set);

Similar Questions: Helpful but not quite what I'm looking for类似问题:有帮助但不是我想要的

Update更新

As I suspected the point I was missing is that setting set.length doesn't add elements to the array it only creates a sparse array (an array with gaps).正如我怀疑我遗漏的一点是设置set.length不会向数组添加元素,它只会创建一个稀疏数组(一个有间隙的数组)。 In my case you cannot use for in because there isn't anything in the array to iterate over.在我的情况下,你不能使用for in因为没有数组遍历东西。 I would either have to populate the array with dummy content(ie empty strings) or, more logically, separate the range part I tried to implement with the .length property into a separate range variable.我要么必须用虚拟内容(即空字符串)填充数组,或者,更合乎逻辑地,将我试图用.length属性实现的范围部分分离到一个单独的range变量中。

Working version工作版本

var set = [], range = 50;

for(var i = 0; i < range; i++){
    set[i]=Math.floor((Math.random() * 500) + 1);
}

console.log(set);

It sounds to me like you want to create a static sized array with dynamic content.在我看来,您想创建一个包含动态内容的静态大小的数组。 If this is the case, you need to create the array with the proper size first.如果是这种情况,您需要先创建具有适当大小的数组。 That would create the array for you.这将为您创建数组。 However, you could auto-populate the array with the random values you wanted like so:但是,您可以使用您想要的随机值自动填充数组,如下所示:

var N = 50;
var set = Array.apply(null, {length: N}).map(Function.call, Math.random);

Once the array is auto-populated, the rest of your code should work as expected, by simply using the value of the random number in the array so:数组自动填充后,其余代码应按预期工作,只需使用数组中随机数的值即可:

for(var i in set){
    set[i] = Math.floor(set[i] * 500) + 1;
}
console.log(set);
// OUTPUT
// [267, 219, 293, 298, 403, 70, 162, 270, 434, 292, 433, 478, 476, 
//  311, 268, 266, 105, 242, 255, 250, 206, 104, 142, 406, 50, 139, 
//  364, 375, 47, 480, 445, 149, 91, 228, 404, 267, 298, 158, 305, 
//  311, 92, 377, 490, 65, 149, 431, 28, 452, 353, 494]

This is where I got this: Create a JavaScript array containing 1...N这是我得到的地方: 创建一个包含 1...N 的 JavaScript 数组

It returns undefined because you are setting the array length with set.length .它返回 undefined 因为您正在使用set.length设置数组长度。 When this is called, all elements of the array are undefined调用 this 时,数组的所有元素都undefined

I'd remove the set.length line altogether.我会完全删除set.length行。

Updated code更新代码

var set = [];
for (i = 0; i <= 50; i++) {
  set.push(Math.floor(Math.random() * 500))
}

console.log(set)
=> [138, 215, 149, 180, 348, 497, 88, 156, 238, 439, 130, 185, 20, 116, 330, 131, 188, 257,
    260, 1, 469, 482, 208, 494, 26, 374, 281, 403, 403, 137, 156, 243, 378, 281, 329,
    84, 471, 429, 120, 381, 456, 471, 36, 395, 299, 497, 151, 210, 80, 310]

for in does not seem like what you want here. for in这里似乎不是您想要的。 Try a for loop:尝试for循环:

var set = [], 
    i = 0, 
    l = null;

set.length = 50;

for(; l = set.length; i < l; i++){
    set[i] = Math.floor((Math.random() * 500) + 1);
}

console.log(set);

The issue is not with the array.length property, it is that this method of enlarging the array does not create "properties."问题不在于array.length属性,而是这种扩大数组的方法不会创建“属性”。 Note the following:请注意以下事项:

> [ /*hole*/ , /*hole*/ ,] // An array with two "holes"
[ ,  ]
> new Array(2) // Another way to create an array with two holes
[ ,  ]
> [ undefined, undefined ] // An array with two undefined elements -- not the same
[ undefined, undefined ]
> Object.getOwnPropertyNames([undefined, undefined]);
[ '0', '1', 'length' ]
> Object.getOwnPropertyNames([,,]);
[ 'length' ] // Doesn't have any integer properties!

What you're doing is creating an array with zero elements, then expanding it to include 50 "holes," like the array with two holes.您正在做的是创建一个具有零元素的数组,然后将其扩展为包含 50 个“孔”,就像具有两个孔的数组一样。 Since this array has no enumerable properties ( length isn't enumerable), you can't iterate over it using for...in .由于此数组没有可枚举的属性( length不可枚举),因此您无法使用for...in对其进行迭代。 Ultimately, you would be better off using a traditional for loop.最终,您最好使用传统的for循环。

EDIT编辑

The best definition of a "hole" that I can come up with on the spot is a nonexistent property of an array whose name is an integer i such that 0 <= i && i < array.length .我可以当场想到的“洞”的最佳定义是数组的不存在属性,其名称是整数i使得0 <= i && i < array.length (In considering this, it is important to note that JavaScript arrays are just objects with numeric properties called "indices" and a few extra special features.) (考虑到这一点,重要的是要注意 JavaScript 数组只是具有称为“索引”的数字属性和一些额外的特殊功能的对象。)

There are two ways for a property reference to return undefined: either the property doesn't exist or the property exists and contains the value undefined.属性引用返回 undefined 有两种方式:属性不存在或属性存在并包含值 undefined。 Thus:因此:

> myObject = { myProp: 1, otherProp: undefined }
{ myProp: 1, otherProp: undefined }
> myObject.nonExistentProperty
undefined
> myObject.otherProp
undefined

Now, a hole is a nonexistent property, like myObject.nonExistentProperty above, so trying to access it will cause it to return undefined .现在,一个洞是一个不存在的属性,就像上面的myObject.nonExistentProperty一样,所以尝试访问它会导致它返回undefined

The second link seems to have your answer.第二个链接似乎有你的答案。

The for (var item in array) looks at your array and, for each item in the array, stores that item in "item" and lets you iterate over each item. for (var item in array)查看您的数组,对于数组中的每个项目,将该项目存储在“item”中,并让您遍历每个项目。 Setting the array.length does not give you any items in the array, and thus the for in does not execute at all - there is nothing to iterate over.设置 array.length 不会为您提供数组中的任何项目,因此for in根本不执行 - 没有任何可迭代的内容。

the best and easiest way to fill an array with filler value can be simply be done by instantiating the Array() class and then use the Array.protype.fill() method to give it value.用填充值填充数组的最佳和最简单的方法可以简单地通过实例化Array()类然后使用Array.protype.fill()方法为其赋值。

const array_filler = new Array(10).fill(20)

for further reference, you can read the following article如需进一步参考,您可以阅读以下文章

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

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