扩展语法如何影响数组拼接 [英] How does the spread syntax affect array splice
问题描述
我发现以下代码,我不知道A和B之间有什么区别:
I found the following code and I don't know what is the difference between A and B:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
A
fruits.splice(2,0,["Lemon", "Kiwi"]);
B
fruits.splice(...[2,0].concat(["Lemon", "Kiwi"]));
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var A = fruits.splice(2, 0, ["Lemon", "Kiwi"]);
var B = fruits.splice(...[2, 0].concat(["Lemon", "Kiwi"]));
console.log(A)
console.log(B)
推荐答案
首先,声明A&声明B将生成不同的结果。
First of all, Statement A & Statement B will generate different results.
在语句A
中,您正在插入一个数组( [Lemon, Kiwi]
)作为位置2的数组元素,同时删除0个项目。所以,你在一个位置2的另一个字符串数组中插入一个字符串数组。
In Statement A
, you are inserting an array (["Lemon", "Kiwi"]
) as an array element at position 2 while removing 0 items. So, you are inserting a string array in another string array at position 2.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,["Lemon", "Kiwi"]);
console.log(fruits);
然而,声明B
更有趣。为了完全理解它,首先注销它的核心部分如下:
However, Statement B
is much more interesting. To, understand it fully, first log out it's core portion like this:
console.log(...[2,0].concat(["Lemon", "Kiwi"])); // basic array concatenation then spread
正如你所看到的那样生成, 2 0柠檬奇异果
。然后它作为参数传递给 fruits.splice(.. here ..)
。根据 array#splice
它将在第2位输入两个字符串(Lemon& Kiwi),同时删除0个元素。
As you can see it generates, 2 0 Lemon Kiwi
. Then it is passed as parameter to fruits.splice(..here..)
. According to array#splice
it will enter two strings (Lemon & Kiwi) at position 2, while removing 0 elements.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(...[2,0].concat(["Lemon", "Kiwi"]));
// is same as fruits.splice(2, 0, 'Lemon', 'Kiwi')
console.log(fruits);
注意:
-
array#splice
更新原始数组。 -
声明A
插入数组
(IE[父字符串数组中的Lemon,Kiwi]
),而语句B
插入两个字符串(IE'Lemon','Kiwi'
)在父字符串数组中。
array#splice
updates the original array.Statement A
inserts anarray
(IE["Lemon", "Kiwi"]
) in parent string array whereas,Statement B
inserts two strings (IE'Lemon', 'Kiwi'
) in parent string array.
这篇关于扩展语法如何影响数组拼接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!