如何用 JavaScript 编写扩展方法

问题描述 投票:0回答:2

以下代码向

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

达到这个结果的技术是什么?

javascript arrays extension-methods
2个回答
0
投票

使用数组上的

splice
方法删除
index
上的一项。
splice 方法将返回一个包含已删除项目的数组(在我们的情况下只是一个包含一项的数组),您可以通过索引访问该项目
0

Array.prototype.remove = function (index) {
  const removedItems = this.splice(index, 1);
  return removedItems[0];
};

0
投票
  1. 使用名称
    remove
    具有误导性,并且与其他数组方法不匹配,我建议
    removeIndex
  2. 分配给原型会创建一个可枚举属性,在极少数情况下(当有人在数组上使用
    for .. in
    时),它会导致运行时崩溃。因此,将其正确定义为不可枚举
  3. 整个想法没有意义,因为对于相同的操作已经有一个标准
    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);

© www.soinside.com 2019 - 2024. All rights reserved.