gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:28:20 25 4
gpt4 key购买 nike

任何人都可以解释如何在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com