JavaScript For-each/For-in 循环改变元素类型

发布于 2024-11-09 10:13:27 字数 406 浏览 0 评论 0原文

可能的重复:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半山落雨半山空 2024-11-16 10:13:27

我认为你误解了 JavaScript for...in 的作用。它不会迭代数组元素。它迭代对象属性。 JavaScript 中的对象有点像其他语言中的字典或哈希,但由字符串作为键控。特别是,数组被实现为对象,其属性是从 0N-1 的整数 - 但是,由于所有属性名称都是字符串,因此深层次的索引也是如此。

现在让我们举一个与 [0] 稍有不同的示例,因为这里的索引与值一致。我们来讨论一下[2]

因此,如果我们忽略从 Array 继承的内容,[2]{ "0": 2 } 几乎相同。

for..in 将迭代属性 names,它将选取 "0",而不是 2

现在,您可能会问,如何迭代Array?通常的方法是:

var arrayLen = array.length;
for (var i = 0; i < arrayLen; i++) {
  var el = array[i];
  // ...
}

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 Arrays then, you ask? The usual way is:

var arrayLen = array.length;
for (var i = 0; i < arrayLen; i++) {
  var el = array[i];
  // ...
}
旧人哭 2024-11-16 10:13:27

for-in 语句枚举对象的属性。在您的情况下 element 是属性的名称,并且始终是一个字符串。

The for-in statement enumerates the properties of an object. In your case element is the name of the property and that is always a string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文