【问题标题】:How to remove first array element using the spread syntax如何使用扩展语法删除第一个数组元素
【发布时间】:2019-01-31 22:55:23
【问题描述】:

所以我有一个数组,例如。 const arr = [1, 2, 3, 4];。我想使用扩展语法... 删除第一个元素。

即。 [1, 2, 3, 4] ==> [2, 3, 4]

这可以用展开语法来完成吗?

编辑:为更一般的用例简化了问题。

【问题讨论】:

  • 为什么不直接使用splice呢? arr.splice(1,1) 应该按照你的要求去做
  • 甚至arr.shift()
  • 谢谢,我知道我可以使用这些方法,我只是想了解更多关于...的具体信息

标签: javascript arrays spread-syntax


【解决方案1】:

Destructuring assignment

var a = [1, 2, 3, 4];

[, ...a] = a

console.log( a )

【讨论】:

    【解决方案2】:

    当然可以。

    const xs = [1,2,3,4];
    
    const tail = ([x, ...xs]) => xs;
    
    console.log(tail(xs));

    这就是你要找的吗?


    您最初想删除足够简单的第二个元素:

    const xs = [1,0,2,3,4];
    
    const remove2nd = ([x, y, ...xs]) => [x, ...xs];
    
    console.log(remove2nd(xs));

    希望对您有所帮助。

    【讨论】:

    • 这太好了,谢谢!通过这些答案了解了很多关于... 运算符的知识
    【解决方案3】:

    这是你要找的吗?

    const input = [1, 0, 2, 3, 4];
    const output = [input[0], ...input.slice(2)];
    

    问题更新后:

    const input = [1, 2, 3, 4];
    const output = [...input.slice(1)];
    

    但这很愚蠢,因为你可以这样做:

    const input = [1, 2, 3, 4];
    const output = input.slice(1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-14
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多