JavaScript For-each/For-in 循环改变元素类型
可能的重复:
JavaScript“For …in”与数组
我正在尝试使用 for-in循环遍历数字数组的语法。问题是,这些数字正在转换为字符串。
for(var element in [0]) {
document.write(typeof(element)); // outputs "string"
}
这是标准行为吗?我可以想出很多方法来解决它,但我实际上只是在寻找解释,以扩展我对 JavaScript 的理解。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你误解了 JavaScript
for...in
的作用。它不会迭代数组元素。它迭代对象属性。 JavaScript 中的对象有点像其他语言中的字典或哈希,但由字符串作为键控。特别是,数组被实现为对象,其属性是从0
到N-1
的整数 - 但是,由于所有属性名称都是字符串,因此深层次的索引也是如此。现在让我们举一个与
[0]
稍有不同的示例,因为这里的索引与值一致。我们来讨论一下[2]
。因此,如果我们忽略从
Array
继承的内容,[2]
与{ "0": 2 }
几乎相同。for..in
将迭代属性 names,它将选取"0"
,而不是2
。现在,您可能会问,如何迭代
Array
?通常的方法是: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 from0
toN-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 fromArray
, pretty much the same as{ "0": 2 }
.for..in
will iterate over property names, which will pick up the"0"
, not the2
.Now, how to iterate over
Array
s then, you ask? The usual way is:这是为什么在数组迭代中使用“for...in”是一个坏主意?
This is a repeat of Why is using "for...in" with array iteration a bad idea?
for-in
语句枚举对象的属性。在您的情况下element
是属性的名称,并且始终是一个字符串。The
for-in
statement enumerates the properties of an object. In your caseelement
is the name of the property and that is always a string.