how is adding elements different from removing elements using splice() with javascript;
this code is confusing me; please help me:
code:
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']
months.splice(4, 1, 'May');
// replaces 1 element at 4th index
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
hey, adding or removing is based on the parameters we pass to it
array.splice( start, end ) to remove items
array.splice(start, 0, item1,item2, ... ) to add items
if we pass two parameters it removes items from start to end
if we pass three parametesrs (end = 0 means do not remove any) add items from start index
if end = n remove n items first then add items passed from third parameter
is it slice or splice or does it work the same?
1 Like
sorry my mistake it is splice()
I want to copy all the elements of an array into another do I have to list all the elements or does it accept a callback function?
use es6 array destructuring syntax like this ...arr
arr.splice(start, end, ...arr)
1 Like
thanks a lot, it is working for now.