我正在使用myarray.length = 0
方法通过自定义Array.prototype.clear()
方法截断数组。通过将长度设置为0截断数组中的数组无效
到目前为止,据我所知,但我现在有一个特殊情况,它将length
设置为0
,但元素仍然存在。
我运行了一个基本的数组测试,它似乎工作,但在这个更复杂的情况下,它不是,所以很难诊断问题。
这里是我的Array.prototype
,我已经使用扩展代码...
Object.defineProperty(Array.prototype, 'clear', {
value: function clear() {
// Clear the array using the length = 0 method. See the method's comments on links to more information and benchmarks on this technique.
this.length = 0;
},
enumerable: false,
configurable: true,
writable: false
});
当我把它在其他情况下,下面的工作出色。
var myarray = [ 1,2,3,4,5,6,6,7,8,9, new Date() ];
myarray.clear();
console.log(myarray); // all cleared. { length: 0 }
但我更复杂的情况下阵列具有约10-20元,我所说的阵列上的.clear()
,它设置长度0
但如果我console.log
像数组中的元素仍然可以看到我在上面做了。
// e.g. { 0: ..., 1: ..., 2: ..., 3: ..., 4: ..., length: 0 }
唯一的区别是,Array
对象我使用是扩展对象,具有一个覆盖,这确实调用重写的函数。像这样......
function Collection() { Array.apply(this); }
Collection.prototype = Object.create(Array.prototype, {
push: {
enumerable: false,
value: function(item) {
// ...does a type checks on 'item'
Array.prototype.push.apply(this, [ item ]);
}
},
clear: {
enumerable: false,
value: function() { Array.prototype.clear.apply(this); }
}
});
这是发生在Chrome,我已加强它通到Array.prototype.clear
方法,就像我的测试一样,但由于某种原因,它不会在第二种情况下工作。
任何想法?
好像ÿ你试图在一个对象上使用它,而在一个对象上使用“长度”只是另一个属性,并且不会改变对象的内容。请注意,扩展本地原型通常是一个糟糕的主意 – adeneo
我并不认为扩展本地代码是个不错的主意......除了“Array” - 与其他本地代码相比,它具有“魔力” –
@JaromandaX - 它是并不总是一个坏主意,但它通常是一个坏主意,这意味着我认为应该避免它,例如在这种情况下,一个普通的“清除(Array)”可以做同样的事情,而不用触摸原型。至少它不是可枚举的。 – adeneo