[英]When i use Array.splice(), it's like i'm using Array.slice()?
so i just noticed that when i use Array.splice() it's like i'm using Array.slice(), 所以我只是注意到当我使用Array.splice()时,就像我在使用Array.slice()一样,
So when i type [0, 1, 2, 3].splice(0, 2)
it returns [0, 1]
? 因此,当我键入
[0, 1, 2, 3].splice(0, 2)
它将返回[0, 1]
? (yes i am shure that i'm typing splice
not slice
) (是的,我很确定我正在输入
splice
而不是slice
)
So basicly: 所以基本上:
[0, 1, 2, 3, 4, 5].splice(0, 2);
returns [0, 1]?
[0, 1, 2, 3, 4, 5].splice(3, 1);
returns [3]?
[0, 1, 2, 3, 4, 5].slice(0, 2);
returns [0, 1]
[0, 1, 2, 3, 4, 5].slice(3, 1);
returns [3]
Why does this happen? 为什么会这样? It's supposed to remove the specified objects right?
应该删除指定的对象吧?
slice
takes a copy of a section of the array and returns it. slice
获取数组部分的副本并返回它。
splice
removes a section of the array and returns it. splice
删除数组的一部分并返回它。 An optional parameter allows replacing those elements with others as well. 可选参数还允许将这些元素替换为其他元素。
The splice method modifies the contents of the array on which you are calling. splice方法修改您要在其上调用的数组的内容。
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。
Whereas, the slice method returns the new array copy from the given range of index. 而slice方法则从给定的索引范围返回新的数组副本。
The slice() method returns a shallow copy of a portion of an array into a new array object.
slice()方法将数组的一部分的浅表副本返回到新的数组对象中。
It returns the same thing, sure, except slice does not mutate the original array. 当然,它返回的是相同的东西,除了slice不会改变原始数组。 Splice, on the other hand returns what was removed from the original array.
另一方面,拼接返回从原始数组中删除的内容。
splice()
replaces items with other items, altering the input array. splice()
用其他项目替换项目,从而改变了输入数组。 slice()
just takes from an array without altering it. slice()
只是从数组中获取而没有对其进行更改。 Since you're not using a variable as input, you'll never see the difference. 由于您没有使用变量作为输入,因此您永远不会看到差异。 But try this:
但是尝试一下:
a = [4, 5, 6, 7, 8]
> [4, 5, 6, 7, 8]
a.splice(2, 2)
> [6, 7]
a
> [4, 5, 8]
a
has changed. a
已经改变。 That's splice()
那是
splice()
The real power comes from substitution/replacement: 真正的力量来自替代/替换:
a = [3, 4, 5, 6, 7]
> [3, 4, 5, 6, 7]
a.splice(2, 2, 500, 600)
> [5, 6]
a
> [3, 4, 500, 600, 7]
If you have an array of items to 'splice' into the array, you have to use .apply
: 如果您有要“拼接”到数组中的项目数组,则必须使用
.apply
:
a = [3, 4, 5, 6, 7]
> [3, 4, 5, 6, 7]
b = [500, 600]
> [500, 600]
a.splice.apply(a, [2, 2].concat(b))
> [5, 6]
a
> [3, 4, 500, 600, 7]
Or make your own function that does that more readable. 或者使您自己的函数更具可读性。
You can also splice-add items into an array, by making the 2nd argument 0: a.splice(2, 0, 500, 600)
. 您还可以通过将第二个参数
a.splice(2, 0, 500, 600)
0: a.splice(2, 0, 500, 600)
将项目拼接添加到数组中。
You can read all this, and more, in the docs! 您可以在文档中阅读所有这些内容以及更多内容!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.