gpt4 book ai didi

for循环期间的Javascript关联数组修改

转载 作者:数据小太阳 更新时间:2023-10-29 05:13:41 26 4
gpt4 key购买 nike

javascript for 关键字将遍历对象的所有属性。如果对象在循环体内被修改,会发生什么?

比如下面的代码可以吗?

for(var key in obj)
if (whatever(obj[key]))
delete obj[key];

如果此代码以确定性方式工作并且最好是 obj 中的所有键都只测试一次就可以了。相比之下,在 .NET 或 Java 中,类似的构造通常会引发异常。

最佳答案

我觉得可行。请小心请求 hasOwnProperty(key) - 因为 for 也会愉快地迭代继承的属性(和方法,它们只是具有函数值的属性)。

还有:http://www.w3schools.com/js/js_loop_for_in.asp说:

Note: The code in the body of the for...in loop is executed once for each property.

还有:https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in说:

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). If a property is modified in one iteration and then visited at a later time, the value exposed by the loop will be its value at that later time. A property which is deleted before it has been visited will not then be visited later. 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.

我从中读到的是 - 如果您正在修改当前值以外的值,则不确定性可能会咬您的屁股。但是,修改当前的应该没问题。

关于for循环期间的Javascript关联数组修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6081868/

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