JavaScript For-each / For-in循环更改元素类型 [英] JavaScript For-each/For-in loop changing element types
问题描述
可能重复:
JavaScript为...…在”与数组
我试图使用for-in语法来循环通过一系列的数字。
for(var element in [0]){
document .WRITE(typeof运算(元件)); //输出string
}
这是标准行为吗?我可以想到一些方法来解决它,但我真的只是寻找解释,以扩大我对JavaScript的理解。
解决方案 / div>我想你误解了< for
。它不会迭代数组元素。它迭代对象的属性。 JavaScript中的对象类似于其他语言的字典或散列,但是由字符串键入。数组特别是被实现为具有从
0
到 N-1
的整数的对象 - 然而,因为所有属性名称是字符串,深度也是索引。
现在我们来看一个与 [0] $ c $不同的示例因为这里指数与价值重合。我们来讨论
[2]
。
因此, [2]
是,如果我们忽略从 Array
继承的东西,几乎与 {0:2}
$ b $ for..in
将遍历属性名称,会选择0
,而不是 2
。
现在,如何迭代 Array
s,那么你问?通常的方法是:
var arrayLen = array.length;
for(var i = 0; i< arrayLen; i ++){
var el = array [i];
// ...
}
Possible Duplicate:
JavaScript “For …in” with Arrays
I'm trying to use the for-in syntax to loop through an array of numbers. Problem is, those numbers are getting converted to strings.
for(var element in [0]) {
document.write(typeof(element)); // outputs "string"
}
Is this standard behavior? I can think of a bunch of ways to work around it, but I'm really just looking for an explaination, to expand my understanding of JavaScript.
I think you misunderstand what JavaScript for...in
does. It does not iterate over the array elements. It iterates over object properties. Objects in JavaScript are kind of like dictionaries or hashes in other languages, but keyed by strings. Arrays in particular are implemented as objects which have properties that are integers from 0
to N-1
- however, since all property names are strings, so are the indices, deep down.
Now let's take a bit different example than [0]
, since here index coincides with the value. Let's discuss [2]
instead.
Thus, [2]
is, if we ignore the stuff we inherit from Array
, pretty much the same as { "0": 2 }
.
for..in
will iterate over property names, which will pick up the "0"
, not the 2
.
Now, how to iterate over Array
s then, you ask? The usual way is:
var arrayLen = array.length;
for (var i = 0; i < arrayLen; i++) {
var el = array[i];
// ...
}
这篇关于JavaScript For-each / For-in循环更改元素类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!