javascript 中的语句是为....
任何人都可以解释如何在 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>
anyone can explain how to use for...in statement in javascript. I had read the w3school article but i think it is not so clear.Below is the code, please explain this:
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
for in
循环将迭代对象中的每个属性。在您的示例中,
x
变量将循环访问mycars
对象中的每个属性。如果您添加
mycars.expense = "Porsche";
,它也会发现这一点。请注意,正如MDC所述,
for in
循环不应该用于循环普通数组:A
for in
loop will iterate through every property in an object.In your example, the
x
variable will cycle through every property in themycars
object.If you add
mycars.expensive = "Porsche";
, it will find that too.Note that, as stated by MDC,
for in
loops should not be used to loop through ordinary arrays:首先,您创建一个包含 3 个项目(而不是数组)的对象
,其中
10
、20
和30
是对象属性。那么您想要浏览该对象,访问所有属性并显示与属性关联的每个值。
这是 [
for
(variablein
object) expression ] javascript 构造的地方干预:变量将被设置为对象的第一个属性,然后是第二个属性,然后是最后一个属性。尝试
看看它是如何工作的,还有这个
First you create an object with 3 items (and not an Array)
where
10
,20
and30
are the object properties.then you want to navigate through the object, visit all properties and display each value associated to a property.
This is where the [
for
(variablein
object) expression ] javascript construction intervenes:The variable will be set to the first property of the object, then to the 2nd, then to the last. Try
to see how it works, and this as well
for ... in
结构迭代in
右侧对象内的每个元素。在您的例子中,for
语句下面的块会针对mycars
中的每辆车执行一次。The
for ... in
construction iterates over every element within the object on the right side ofin
. In your case, the block below thefor
statement is executed once for every car inmycars
.for in
是一种埋藏bug以供后人发现的方式。正如已经大量指出的那样,如果应用于数组,它将循环遍历数组的所有元素、数组的长度以及附加到数组的任何其他数据。将其应用于普通对象会更好,但您仍然应该通过hasOwnProperty
过滤索引。最好使用框架提供的函数,例如 jQuery 的
$.each
for in
is a way of burying bugs for later generations to discover. As has been copiously pointed out, if applied to an Array, it will loop through all the elements of the array, and the length of the array, and whatever other data happens to be attached to the array. Applying it to an ordinary object is better, but you still should still filter the indices throughhasOwnProperty
.Better to use a framework-provided function like jQuery's
$.each