【问题标题】:How to remove element from an array in JavaScript?如何从 JavaScript 中的数组中删除元素?
【发布时间】:2011-01-01 12:11:04
【问题描述】:
var arr = [1,2,3,5,6];

删除第一个元素

我想删除数组的第一个元素,使其变为:

var arr = [2,3,5,6];

移除第二个元素

为了扩展这个问题,如果我想删除数组的第二个元素,让它变成:

var arr = [1,3,5,6];

【问题讨论】:

  • slice(start, end) not 'how_many_to_remove'
  • @Ped arr.unshift() 不会删除,而是“将一个或多个元素添加到数组的开头”
  • @seanjacob 我猜是splice 不是slice

标签: javascript arrays


【解决方案1】:

要获得更灵活的解决方案,请使用splice() 函数。它允许您根据索引值删除数组中的任何项目:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);

【讨论】:

  • 以及后续问题:arr.splice(1,1) 用于第二个元素。
  • 我更喜欢splice() 而不是shift(),因为它更灵活。我将来可能想做一些不同的事情,而且我并不总是只想删除一个元素,甚至是第一个元素。
  • 如果您来自 Google:Gabriel 更喜欢这个答案,但您应该知道还有 shift(),请参阅 Joseph 的答案。
【解决方案2】:

可能是这样的:

arr=arr.slice(1);

【讨论】:

    【解决方案3】:

    shift() 非常适合您的情况。 shift() 从数组中删除第一个元素并返回该元素。这个方法改变了数组的长度。

    array = [1, 2, 3, 4, 5];
    
    array.shift(); // 1
    
    array // [2, 3, 4, 5]
    

    【讨论】:

    • 这可行,但只会删除数组中的第一个元素。
    • @Gabriel:不正是这个问题吗?我更喜欢shift() 而不是splice(..., ...),因为它更明确、更直接。
    • 更正:根据您提供的链接,它返回第一个元素,而不是减去第一个元素的新数组:)
    • 虽然代码示例是正确的,但 描述 具有误导性:(a) 正如@DanH 指出的那样,它是返回的第一个元素,以及 (b) 输入数组已修改这一事实并不清楚。因此,Ped 的答案更胜一筹。
    • shift 更快,除非您拼接大型列表 jsperf.com/splice-vs-shift3jsperf.com/splice-vs-shift2
    【解决方案4】:

    写了一篇关于在 Javascript Arrays 中任意位置插入和删除元素的小文章。

    这是从任何位置删除元素的小 sn-p。这扩展了 Javascript 中的 Array 类并添加了 remove(index) 方法。

    // Remove element at the given index
    Array.prototype.remove = function(index) {
        this.splice(index, 1);
    }
    

    所以要删除示例中的第一项,请调用 arr.remove():

    var arr = [1,2,3,5,6];
    arr.remove(0);
    

    要删除第二个项目,

    arr.remove(1);
    

    这是一个很小的article,带有 Array 类的插入和删除方法。

    本质上,这与使用 splice 的其他答案没有什么不同,但名称 splice 不直观,如果您在整个应用程序中都有该调用,它只会使代码更难阅读。

    【讨论】:

      【解决方案5】:
      arr.slice(begin[,end])
      

      是非破坏性的,拼接和移位会修改你原来的数组

      【讨论】:

      • 是的,非变异。这应该更明显。
      【解决方案6】:

      Array.prototype.shift 方法从数组中删除第一个元素,并将其返回。它修改了原始数组。

      var a = [1,2,3]
      // [1,2,3]
      a.shift()
      // 1
      a
      //[2,3]
      

      【讨论】:

      • 对 Joseph Silvashy 的回答有了很大的改进 - 描述和代码之间没有不一致。
      【解决方案7】:

      Array.splice() 有一个有趣的属性,即不能使用它来删除第一个元素。所以,我们需要求助于

      function removeAnElement( array, index ) {
          index--;
      
          if ( index === -1 ) {
              return array.shift();
          } else {
              return array.splice( index, 1 );
          }
      }
      

      【讨论】:

      • Array.splice(0,1) 删除第一个元素。根据此处的所有其他答案,并根据developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。另外,为什么有人会通过 -1 来删除第一个元素?他们不会通过 0 吗?
      • @skypecakes 我不能谈论在第 0 个索引上拼接的有效性,但是这里的索引在检查之前是递减的,所以传入时它会是 0。
      • 是的,它绝对可以删除第一个元素。我在这里测试过:jsfiddle.net/sijpkes/d87rcLob/2
      【解决方案8】:

      其他答案很好,我只是想用ES6 数组函数添加一个替代解决方案:filter

      filter() 创建一个新数组,其中包含现有数组中给定条件下的元素。

      因此您可以轻松地使用它来删除不符合条件的项目。这个函数的好处是你可以在复杂的数组上使用它,而不仅仅是字符串和数字。

      一些例子:

      删除第一个元素

      // Not very useful but it works
      function removeFirst(element, index) {
        return index > 0;
      }
      var arr = [1,2,3,5,6].filter(removeFirst); // [2,3,4,5,6]
      

      删除第二个元素

      function removeSecond(element, index) {
        return index != 1;
      }
      var arr = [1,2,3,5,6].filter(removeSecond); // [1,3,4,5,6]
      

      移除奇数元素

      function removeOdd(element, index) {
        return !(element % 2);
      }
      var arr = [1,2,3,5,6].filter(removeOdd); [2,4,6]
      

      移除没有库存的商品

      const inventory = [
        {name: 'Apple', qty: 2},
        {name: 'Banana', qty: 0},
        {name: 'Orange', qty: 5}
      ];
      
      const res = inventory.find( product => product.qty > 0);
      
      
      

      【讨论】:

        【解决方案9】:

        您可以将 ES6 解构赋值功能与 rest 运算符一起使用。逗号表示要删除元素的位置,其余 (...arr) 运算符表示数组的剩余元素。

        const source = [1,2,3,5,6];
        
        function removeFirst(list) {
           var  [, ...arr] = list;
           return arr;
        }
        const arr = removeFirst(source);
        console.log(arr); // [2, 3, 5, 6]
        console.log(source); // [1, 2, 3, 5, 6]

        【讨论】:

          【解决方案10】:

          你也可以用 reduce 来做到这一点:

          let arr = [1, 2, 3]
          
          arr.reduce((xs, x, index) => {
                  if (index == 0) {
                      return xs
                  } else {
                      return xs.concat(x)
                  }
              }, Array())
          
          // Or if you like a oneliner
          arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())
          

          【讨论】:

            【解决方案11】:

            不改变原始数组的打字稿解决方案

            function removeElementAtIndex<T>(input: T[], index: number) {
              return input.slice(0, index).concat(input.slice(index + 1));
            }
            

            【讨论】:

              【解决方案12】:

              有多种方法可以从数组中删除元素。让我指出下面最常用的选项。我正在写这个答案,因为我找不到从所有这些选项中使用什么的适当理由。问题的答案是选项 3 (Splice())。

              1) SHIFT() - 从原始数组中删除第一个元素并返回第一个元素

              请参阅Array.prototype.shift() 的参考资料。仅当您想删除第一个元素并且仅当您可以更改原始数组时才使用此选项。

              const array1 = [1, 2, 3];
              
              const firstElement = array1.shift();
              
              console.log(array1);
              // expected output: Array [2, 3]
              
              console.log(firstElement);
              // expected output: 1
              

              2) SLICE() - 返回数组的副本,由开始索引和结束索引分隔

              请参阅Array.prototype.slice() 的参考资料。您不能从此选项中删除特定元素。您只能对现有数组进行切片并获得数组的连续部分。这就像从您指定的索引中剪切数组一样。原数组不受影响。

              const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
              
              console.log(animals.slice(2));
              // expected output: Array ["camel", "duck", "elephant"]
              
              console.log(animals.slice(2, 4));
              // expected output: Array ["camel", "duck"]
              
              console.log(animals.slice(1, 5));
              // expected output: Array ["bison", "camel", "duck", "elephant"]
              

              3) SPLICE() - 通过删除或替换特定索引处的元素来更改数组的内容。

              请参阅Array.prototype.splice() 的参考资料。 splice() 方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。返回更新的数组。原始数组得到更新。

              const months = ['Jan', 'March', 'April', 'June'];
              months.splice(1, 0, 'Feb');
              // inserts at index 1
              console.log(months);
              // expected output: Array ["Jan", "Feb", "March", "April", "June"]
              
              months.splice(4, 1, 'May');
              // replaces 1 element at index 4
              console.log(months);
              // expected output: Array ["Jan", "Feb", "March", "April", "May"]
              

              【讨论】:

                猜你喜欢
                • 2015-10-28
                • 1970-01-01
                • 2022-12-26
                • 2020-02-12
                • 2018-08-13
                • 2011-03-14
                • 2022-11-03
                • 1970-01-01
                相关资源
                最近更新 更多