有时 array.length 只在 .push() 之后工作(为什么?)

Sometimes array.length only works after .push() (WHY?)

本文关键字:工作 为什么 之后 array 只在 push 有时 length      更新时间:2023-09-26
function vertexes() {};
vertexes.prototype = [];
vertexes.prototype.add = function (x, y, z) {
    this.push(new vertex(x, y, z));
    return this[this.length-1];
}

点是包含顶点对象的集合。顶点对象应作为数组访问(顶点[0]是顶点)。上面的代码工作正常。

function vertexes() {};
vertexes.prototype = [];
vertexes.prototype.add = function (x, y, z) {
    this[this.length] = new vertex(x, y, z);
    return this[this.length-1];
}

但是,上面的代码没有。当声明this[this.length]时,它总是声明this[0],并返回undefined。如果 vertexes.prototype 是一个数组,为什么 array.length 只有在 i .push() 一个元素时才起作用?

发生这种情况是因为[]运算符对实际数组具有特殊行为。您正在创建的对象不是数组。

如果您尝试使用原型扩展数组,则基本上将拥有一个带有 Array 方法和默认属性值的普通对象。使用 [] 为其赋值只会导致向其添加属性,而不会影响其长度。

请注意,通过一些微调,可以扩展数组,以便用括号为其分配值会更新长度。它基本上涉及实例化实际数组并将您自己的方法附加到每个新实例。

在这里看到:http://www.bennadel.com/blog/2292-extending-javascript-arrays-while-keeping-native-bracket-notation-functionality.htm

延伸阅读:http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/