如何使用扩展语法删除第一个数组元素

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

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

这可以用展开语法做到吗?

编辑:为了更加通用,简化了问题。


2
为什么不直接使用splice呢?arr.splice(1,1)应该可以实现你所要求的功能。 - David784
甚至包括 arr.shift() - Nick
谢谢,我知道我可以使用这些方法,我只是想更多地了解 ... - coops22
4个回答

14
可以的。

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));

希望这有所帮助。

太棒了,谢谢!通过这些答案学到了很多关于...运算符的知识。 - coops22

13

解构赋值

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

[, ...a] = a

console.log( a )


4
这是你在寻找的吗?
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);

0
您可以使用带有展开运算符 (...arr)rest操作符 (...arrOutput)
const arr = [1, 2, 3, 4];
const [itemRemoved, ...arrOutput] = [...arr];
console.log(arrOutput);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接