自定义Array.prototype.clear方法时赋值this报错,求可行解决方案
Array.prototype.clear的可行实现方案
你原来的代码报错是因为this在函数里是只读引用,没法直接赋值成新数组。下面几种方案都是直接修改原数组,不会创建新对象,完全符合你的需求:
修改length属性(最简单高效)
数组的length属性是可写的,直接设为0就能清空所有元素:function clear() { this.length = 0; } Object.defineProperty(Array.prototype, 'clear', { value: clear, enumerable: true });使用splice方法
调用splice(0)会从数组起始位置删除所有元素,同样是在原数组上修改:function clear() { this.splice(0); } Object.defineProperty(Array.prototype, 'clear', { value: clear, enumerable: true });循环删除元素(不推荐,效率较低)
通过pop()逐个移除末尾元素,直到数组为空,适合理解原理但实际用前两种更优:function clear() { while (this.length > 0) { this.pop(); } } Object.defineProperty(Array.prototype, 'clear', { value: clear, enumerable: true });
内容的提问来源于stack exchange,提问作者Gary
相关产品推荐
相关产品推荐

