gpt4 book ai didi

javascript - for in 循环和删除运算符

转载 作者:可可西里 更新时间:2023-11-01 02:24:37 25 4
gpt4 key购买 nike

我注意到,在枚举对象的属性时,似乎在循环开始时拍摄当前属性的快照,然后迭代快照。我有这种感觉,因为以下内容不会造成无限循环:

var obj = {a:0,b:0}, i=0;
for (var k in obj) {
obj[i++] = 0;
}
alert(i) // 2

演示 http://jsfiddle.net/kqzLG/

上面的代码演示了我正在添加新属性,但是新属性不会被枚举。

但是,删除运算符似乎违背了我的快照理论。这是相同的代码,但在枚举属性之前将其删除。

var obj = {a:0,b:0}, i=0;
for (var k in obj) {
i++;
delete obj.b;
}
alert(i) // 1

演示 http://jsfiddle.net/Gs2vh/

以上代码演示了循环体只执行了一次。如果快照理论成立,它会执行两次。

这是怎么回事? javascript 是否使用某种类型的隐藏迭代器,并且删除运算符以某种方式知道它?

-- 我意识到我假设了一些关于迭代顺序的东西——特别是迭代发生基于属性插入时间。我相信所有浏览器都使用这样的实现。

最佳答案

有趣的问题。答案在于 specification (强调我的):

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified. 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.

所以明确规定了一个被删除的属性不能再遍历了。但是,添加新属性的行为取决于实现,很可能是因为未定义属性应如何在内部存储。

例如在 Chrome 中,数字属性似乎存储在字母属性之前:

> Object.keys({a:0, 0:1});
["0", "a"]

但是,即使您添加字母键:

var obj = {a:0,b:0};
for (var k in obj) {
obj['c'] = 0;
console.log(k);
}

c好像没有遍历,输出的是a b

Firefox 表现出相同的行为,尽管键是按插入顺序存储的:

> Object.keys({a:0, 0:1});
["a", "0"]

关于javascript - for in 循环和删除运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12060907/

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