代码之家  ›  专栏  ›  技术社区  ›  Akira Takeshi

如何用JavaScript编写扩展方法

  •  -1
  • Akira Takeshi  · 技术社区  · 2 年前

    以下代码将一个方法添加到 Array 对象

    Array.prototype.remove = function (index) {
      const temp = [].concat(this);
      return [].concat(temp.slice(0, index)).concat(temp.slice(index + 1));
    };
    
    let arr = [0, 1, 2, 3, 4, 5];
    console.log(arr.remove(3))

    该机制起作用: remove 方法返回一个不同于原始数组的新数组,其中元素位于索引处 index 被移除。

    我想重写 去除 方法,以便它修改起始数组并返回已移除的元素,就像 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
    

    实现这一结果的技术是什么?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Alexander Nenashev    2 年前
    1. 使用名称 remove 具有误导性,并且与其他数组方法不匹配,我建议 removeAt removeIndex 甚至 popAt
    2. 在极少数情况下(当某人使用 for .. in 在数组上),它将导致运行时崩溃。因此,将其正确定义为不可枚举
    3. 整个想法没有意义,因为已经有了一个标准 Array#splice 对于相同的操作

    Object.defineProperty(Array.prototype, 'removeAt', {value: function (index) {
      return this.splice(index, 1)[0];
    }, configurable: true})
    
    const arr = [1,2,3,4,5];
    
    const result = arr.removeAt(2);
    
    console.log(arr, result);

    使用相同 阵列#拼接 :

    const arr = [1,2,3,4,5];
    
    const [result] = arr.splice(2, 1);
    
    console.log(arr, result);
        2
  •  -1
  •   Mina    2 年前

    使用 splice 方法来删除该数组上的一个项 index .
    拼接方法将返回一个带有已删除项的数组(在我们的情况下,它只是一个带有一个项的数组),您可以通过索引访问该项 0

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

    如@jsejcksn所共享,用于Typescript

    interface Array<T> { remove(index: number): T | undefined; }