任何人都可以解释如何在 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 toArray.prototype
), thefor...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/