在遍历对象的属性时,在 for-in 循环中删除它们是否安全?
例如:
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (shouldDelete(obj[key])) {
delete obj[key];
}
}
在许多其他语言中,遍历数组或字典并删除其中的内容是不安全的。在 JS 中可以吗?
(我正在使用 Mozilla 的 Spidermonkey 运行时。)
最佳答案
ECMAScript 5.1 standard第 12.6.4 节(关于 for-in 循环)说:
Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.
所以我认为很明显 OP 的代码是合法的并且会按预期工作。浏览器的怪癖通常会影响迭代顺序和删除语句,但不会影响 OP 代码是否有效。通常最好只删除迭代中的当前属性 - 删除对象中的其他属性将不可预测地导致它们被包含(如果已经访问过)或不包含在迭代中,尽管这可能会或可能不会成为一个问题,具体取决于情况。
另见:
虽然这些都不会真正影响 OP 的代码。
关于javascript - 在遍历对象属性时删除对象属性是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3463048/