以下代码向
Array
对象添加一个方法。
Array.prototype.remove = function (index) {
const temp = [].concat(this);
return [].concat(temp.slice(0, index)).concat(temp.slice(index + 1));
};
该机制有效:
remove
方法返回一个与原始数组不同的新数组,其中索引index
处的元素被删除。
我想重写
remove
方法,以便它修改起始数组并返回删除的元素,就像 Array.prototype.pop
方法的行为一样。
Array.prototype.remove = function (index) {...};
let arr = [0, 1, 2, 3, 4, 5];
let removed = arr.remove(3);
console.log({arr, removed}); // arr: [0, 1, 2, 4, 5], removed: 3
达到这个结果的技术是什么?
使用数组上的
splice
方法删除 index
上的一项。 0
Array.prototype.remove = function (index) {
const removedItems = this.splice(index, 1);
return removedItems[0];
};
remove
具有误导性,并且与其他数组方法不匹配,我建议removeIndex
for .. in
时),它会导致运行时崩溃。因此,将其正确定义为不可枚举Array#splice
Object.defineProperty(Array.prototype, 'removeIndex', {value: function (index) {
return this.splice(index, 1)[0];
}, configurable: true})
const arr = [1,2,3,4,5];
const result = arr.removeIndex(2);
console.log(arr, result);
同样使用
Array#splice
:
const arr = [1,2,3,4,5];
const [result] = arr.splice(2, 1);
console.log(arr, result);