编程语言
首页 > 编程语言> > 什么是…在javascript语句中

什么是…在javascript语句中

作者:互联网

任何人都可以在javascript中解释如何使用… 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 =“保时捷”;它也会发现.

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

Although it may be tempting to use
this as a way to iterate over an 07002,
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 07003 loop with a numeric index when
iterating over arrays. Similar
arguments might be used against even
using for…in at all (at least
without 07004()
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).

标签:for-in-loop,javascript
来源: https://codeday.me/bug/20190726/1544514.html