Javascript Array element append and Remove in the middle

Description

Javascript Array element append and Remove in the middle

 P:To add elements to an array using splice(), you have to provide the following arguments: 
  • The starting index (where you want to begin adding elements)
  • The number of elements to remove (0 when you are adding elements)
  • The elements you want to add to the array

The following program adds elements to the middle of an array:

let nums = [1,2,3,7,8,9]; 
let newElements = [4,5,6]; 
nums.splice(3,0,newElements); /*from  w w  w. j  a  va  2 s  .  c om*/
console.log(nums); // 1,2,3,4,5,6,7,8,9 

The elements spliced into an array can be any list of items passed to the function, not necessarily a named array of items. For example:

let nums = [1,2,3,7,8,9]; 
nums.splice(3,0,4,5,6); //w w w .  j av a2s . c o m
console.log(nums); 

In the preceding example, the arguments 4, 5, and 6 represent the list of elements we want to insert into nums.

Here is an example of using splice() to remove elements from an array:

let nums = [1,2,3,100,200,300,400,4,5]; 
nums.splice(3,4); /*  www  . ja  v  a2s  .co m*/
console.log(nums); // 1,2,3,4,5 



PreviousNext

Related