Removing or adding elements with splice() with javascript

Removing or adding elements with splice() with javascript
0

#1

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']

#2

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


#3

is it slice or splice or does it work the same?


#4

sorry my mistake it is splice()


#5

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?


#6

use es6 array destructuring syntax like this ...arr

arr.splice(start, end,  ...arr)

#7

thanks a lot, it is working for now.