我正在使用myarray.length = 0
通过自定义 chop 数组的方法 Array.prototype.clear()
方法。
据我所知,到目前为止这已经有效,但我现在有一个特殊的情况,它设置 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
方法,就像我的测试一样,但由于某种原因它在第二种情况下不起作用。
有什么想法吗?
最佳答案
如果你使用新的 ES2015+ class
Object.defineProperty(Array.prototype, 'clear', {
value: function clear() {
this.length = 0;
},
enumerable: false,
configurable: true,
writable: false
});
class Collection extends Array {
constructor(...args) {
super(...args);
}
push(...args) {
console.log('overridden push', ...args);
// only push even values for example
super.push(...args.filter(x=>x%2 == 0));
}
}
var x = new Collection();
x.push(1,2,3,4);
console.log('after push', JSON.stringify(x));
x.clear();
console.log('after clear', JSON.stringify(x));
或者您可以避免向数组添加清除
class Collection extends Array {
constructor(...args) {
super(...args);
}
push(...args) {
console.log('overridden push', ...args);
// only push even values for example
super.push(...args.filter(x=>x%2 == 0));
}
clear() {
this.length = 0;
}
}
var x = new Collection();
x.push(1,2,3,4);
console.log('after push', JSON.stringify(x));
x.clear();
console.log('after clear', JSON.stringify(x));
关于javascript - 在 Javascript 中通过将长度设置为 0 来 chop 数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46481919/