for循环期间的Javascript关联数组修改 [英] Javascript associative array modification during for loop

查看:51
本文介绍了for循环期间的Javascript关联数组修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The javascript for keyword will iterate over all properties of an object. If the object is modified within the loop body, what happens?

比如下面的代码可以吗?

For example, is the following code OK?

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

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

OK would be if this code works in a deterministic fashion and preferably that all keys in obj are tested exactly once. By contrast, in .NET or Java similar constructs will typically throw an exception.

推荐答案

我认为它有效.小心请求 hasOwnProperty(key) - 因为 for 也很乐意迭代继承的属性(和方法,它们只是具有函数值的属性).

I think it works. Just be careful to ask for hasOwnProperty(key) - because for will also happily iterate over inherited properties (and methods, which are just properties with function values).

另外:http://www.w3schools.com/js/js_loop_for_in.asp 说:

注意:for...in 循环体中的代码对每个属性执行一次.

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 说:

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.

我从中读到的是 - 如果您要修改当前值以外的值,则不确定性可能会让您大吃一惊.不过,修改当前的应该没问题.

What I read from this is - if you're modifying values other than the current one, the nondeterminism might bite you in the ass. However, modifying the current one should be okay.

这篇关于for循环期间的Javascript关联数组修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆