简体   繁体   English

JavaScript在添加项目时遍历对象

[英]JavaScript looping through an object while adding items

I have the following code segment: 我有以下代码段:

var run = 0;
var obj = {'item1':0,'item2':5,'item3':10};
for (var i in obj){
    run++
    obj['newItem'+run] = 5;
}
return run;

and it returns 3 . 它返回3 But I want it to go on infinitely and eventually crash the browser. 但我希望它无限运行,并最终导致浏览器崩溃。 Is there any way of updating the obj variable while in a for loop? 在for循环中,有什么方法可以更新obj变量吗?

In general, you shouldn't be adding properties to objects over which an iteration is occurring. 通常,您不应该向正在发生迭代的对象添加属性。

Quoting the Mozilla Dev Center : 引用Mozilla开发中心

Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. 添加到发生迭代的对象的属性可以被访问,也可以从迭代中省略。 In general it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited; 通常,最好不要在迭代过程中从对象中添加,修改或删除属性,当前访问的属性除外; there is no guarantee whether or not an added property will be visited, whether a modified property will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted. 无法保证是否将访问添加的属性,是否在修改之前或之后访问已修改的属性,或者在删除之前是否访问已删除的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM