javascript 如何使用 for in 循环动态填充数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30331700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically populate an array using a for in loop
提问by jeanpier_re
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. My guess is that there is something about the array.length
property and it's use that I'm screwing up.
为了返回一个包含set
1 到 500 之间的随机数序列的数组,我尝试重构标准 for 循环for(var i = 0; i< 50; i++)
并且该方法有效,但是当我尝试使用for in
循环进行重构时却没有。我的猜测是这处array.length
房产有些东西,而且我搞砸了它的用途。
TL;DRWhy does this return an array of 50 undefined elements rather than an array of 50 random integers? And is there a way to make this approach work?
TL;DR为什么这会返回一个包含 50 个未定义元素的数组,而不是包含 50 个随机整数的数组?有没有办法让这种方法奏效?
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). In my case you cannot use for in
because there isn't anything inthe array to iterate over. I would either have to populate the array with dummy content(i.e. empty strings) or, more logically, separate the range part I tried to implement with the .length
property into a separate range
variable.
正如我怀疑我遗漏的一点是设置set.length
不会向数组添加元素它只会创建一个稀疏数组(一个有间隙的数组)。在我的情况下,你不能使用for in
,因为没有任何东西在数组遍历。我要么必须用虚拟内容(即空字符串)填充数组,或者,更合乎逻辑地,将我试图用.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);
采纳答案by Hy-
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. 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.
在for (var item in array)
你的阵列和外观,在“项目”的阵列中的每个项目,存储该项目,并用于遍历每个项目。设置 array.length 不会为您提供数组中的任何项目,因此for in
根本不执行 - 没有什么可以迭代的。
回答by GKnight
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 数组
回答by Richard Hamilton
It returns undefined because you are setting the array length with set.length
. When this is called, all elements of the array are undefined
它返回 undefined 因为您使用set.length
. 当这个被调用时,数组的所有元素都是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]
回答by Kevin Boucher
for in
does not seem like what you want here. Try a for
loop:
for in
在这里看起来不像你想要的。尝试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);
回答by Brian McCutchon
The issue is not with the array.length
property, it is that this method of enlarging the array does not create "properties." Note the following:
问题不在于array.length
属性,而是这种扩大数组的方法不会创建“属性”。请注意以下事项:
> [ /*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. Since this array has no enumerable properties (length
isn't enumerable), you can't iterate over it using for...in
. Ultimately, you would be better off using a traditional for
loop.
您正在做的是创建一个具有零元素的数组,然后将其扩展为包含 50 个“孔”,就像具有两个孔的数组一样。由于此数组没有可枚举属性(length
不可枚举),因此您无法使用for...in
. 最终,您最好使用传统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
.(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.)
我可以当场想到的“洞”的最佳定义是数组的不存在属性,该数组的名称是一个整数i
,使得0 <= i && i < array.length
. (考虑到这一点,重要的是要注意 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. Thus:
属性引用返回 undefined 有两种方式:属性不存在或属性存在并包含值 undefined。因此:
> 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
。
回答by Daniel Charles Mwangila
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)
const array_filler = new Array(10).fill(20)
for further reference, you can read the following article
如需进一步参考,您可以阅读以下文章