Tuesday, January 30, 2018

javascript - How does the spread syntax affect array splice



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)




Answer



First of all, Statement A & Statement B will generate different results.



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





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





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





NOTE:




  • array#splice updates the original array.

  • Statement A inserts an array (IE ["Lemon", "Kiwi"]) in parent string array whereas, Statement B inserts two strings (IE 'Lemon', 'Kiwi') in parent string array.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...