javascript - 什么是......在javascript中的声明

标签 javascript for-in-loop

任何人都可以解释如何在 javascript 中使用 for...in 语句。我看过w3school的文章,但我觉得不是很清楚。下面是代码,请解释一下:

<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[10] = "Saab";
mycars[20] = "Volvo";
mycars[30] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>

最佳答案

A for in loop将遍历对象中的每个属性。

在您的示例中,x 变量将循环遍历 mycars 对象中的每个属性。

如果您添加 mycars.expensive = "Porsche";,它也会找到它。


请注意,如 MDC 所述, for in 循环应该用于遍历普通数组:

Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea. The for...in statement iterates over user-defined properties in addition to the array elements, so if you modify the array's non-integer or non-positive properties (e.g. by adding a "foo" property to it or even by adding a method or property to Array.prototype), the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Also, because order of iteration is arbitrary, iterating over an array may not visit elements in numeric order. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays. Similar arguments might be used against even using for...in at all (at least without propertyIsEnumerable() or hasOwnProperty() checks), since it will also iterate over Object.prototype (which, though usually discouraged, can, as in the case of Array.prototype, be usefully extended by the user where are no namespacing concerns caused by inclusion of other libraries which might not perform the above checks on such iterations and where they are aware of the effect such extension will have on their own use of iterators such as for...in).

关于javascript - 什么是......在javascript中的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4559491/

相关文章:

javascript - 在 Redux 中清除数组状态

javascript - 圆 Angular 问题

JavaScript Closure - 推送到数组的匿名函数的奇怪引用功能

javascript - JavaScript 的 for in 循环是否遍历方法?

ios - 如何将一个对象数组的属性分配给另一个字符串数组?

javascript - 如何为 Ajax.ActionLink 应用 CSS

javascript - Angular 单元在 $attr 上测试 $watch

javascript - 在播放音乐时浏览页面

javascript - 为什么对象点表示法在 for...in 循环中不起作用?

swift - 如何在 Swift 中遍历每个键有多个值的字典