我正在阅读有关 JavaScript 的 call
和 apply
方法的教程,并且对示例中使用的“类数组对象”的行为感到困惑:
var arrayLikeObj = {
0: 'Marty',
1: 78,
2: 42,
3: ['Tim', 'Eric', 'Phil'],
length: 4
};
我的理解是这里的 length 属性与 Array.prototype.length
方法完全无关,并且被硬编码以便为对象提供必要的类似数组的属性。
但是,当我pop
这样的类数组对象时:
console.log(Array.prototype.pop.call(arrayLikeObj));
...它的长度属性减少了!
console.log(arrayLikeObj) // Object {0: "Marty", 1: 78, 2: 42, length: 3}
这怎么可能!?
Array.prototype.length
是否以某种方式覆盖对象中现有的 length 属性,将其转换为 length 方法?
让我更加困惑的是,当我声明一个没有硬编码的 length
属性的对象并调用相同的 pop
方法时:
var arrayLikeObj = {
0: 'Marty',
1: 78,
2: 42,
3: ['Tim', 'Eric', 'Phil']
};
console.log(Array.prototype.pop.call(arrayLikeObj));
console.log(arrayLikeObj);
返回的对象已被分配长度为0:
{0: "Marty", 1: 78, 2: 42, 3: Array[3], length: 0}
我非常有兴趣了解这里发生的事情。
最佳答案
Array.prototype.pop
为对象创建一个 length
属性。
http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.6
它发生在步骤 4.a 和 5.d 中。在您发布的第二种情况下,请注意 [[Get]]
内部方法返回 undefined
(因为没有 length
属性),并且ToUint32(undefined)
先将undefined
转为NaN
,再将NaN
转为0
.
关于javascript - 为什么我的类数组对象的长度属性会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22875566/