我注意到MDN在start Parameter的描述中提到:
这个描述对于我删除元素非常有用:
删除第一个元素:
let foo = ["a", "b", "c"];
foo.splice(0,1) // "a" removed
console.log(foo);//["b", "c"]Run Code Online (Sandbox Code Playgroud)
删除最后一个元素:
let foo = ["a", "b", "c"];
foo.splice(-1,1) // "c" removed
console.log(foo);//["a", "b"]Run Code Online (Sandbox Code Playgroud)
现在让我们尝试添加元素
在第 1 处添加元素 :
let foo = ["a", "b", "c"];
foo.splice(0,0,"x") // "x" added to 1st
console.log(foo);//["x", "a", "b", "c"]Run Code Online (Sandbox Code Playgroud)
将元素添加到最后:
let foo = ["a", "b", "c"];
foo.splice(-1,0,"x")
// I expected to added "x" as a last element
// but instead it shows ["a", "b", "x", "c"]
console.log(foo);Run Code Online (Sandbox Code Playgroud)
谁能解释为什么?
最后一种情况显示 ["a", "b", "x" , "c"]
如果你想从它的位置删除相同的元素,我们应该从 -2 而不是 -1 的索引中删除它:
let foo = ["a", "b", "c"];
foo.splice(-1,0,"x")
console.log(foo);
//["a", "b", "x", "c"]
foo.splice(-2,1)
console.log(foo);Run Code Online (Sandbox Code Playgroud)
谢谢...
最初让我们将 foo 视为["a", "b", "c"]3 foo.length。
因此,当您使用 添加元素时foo.splice(-1,0,"x"),索引的计算结果foo.length - 1为 2。
因此新元素被插入到索引 2 处:
["a", "b", "c"]
0 1 2
^
|__________"x" added here
Run Code Online (Sandbox Code Playgroud)
因此,新数组变为["a", "b", "x", "c"]“x”插入到索引 2 处,“c”移动一个索引。
当您使用 删除元素时foo.splice(-2,0),删除该元素的索引foo.length - 2为 2:
["a", "b", "x", "c"]
0 1 2 3
^
|__________ "x" is removed
Run Code Online (Sandbox Code Playgroud)
数组就变成了["a", "b", "c"]。