Javascript Array element append

Description

Javascript Array element append

 P:There are two mutator functions for adding elements to an array:push() and unshift(). 

The push() function adds an element to the end of an array:

let nums = [1,2,3,4,5]; 
console.log(nums); // 1,2,3,4,5 
nums.push(6); //from   w ww  .j  a  va2 s. co  m
console.log(nums); // 1,2,3,4,5,6 

Using push() is more intuitive than using the length property to extend an array:

let nums = [1,2,3,4,5]; 
console.log(nums); // 1,2,3,4,5 
nums[nums.length] = 6; //  w  w  w.  j  ava2s . c  o  m
console.log(nums); // 1,2,3,4,5,6 

The mutator function for adding array elements to the beginning of an array is unshift().

Here is how the function works:

let nums = [2,3,4,5]; 
console.log(nums); // 2,3,4,5 
let newnum = 1; /*ww w. ja v  a  2  s  . c  o m*/
nums.unshift(newnum); 
console.log(nums); // 1,2,3,4,5 
nums = [3,4,5]; 
nums.unshift(newnum,1,2); 
console.log(nums); // 1,2,3,4,5 

The second call to unshift() demonstrates that you can add multiple elements to an array with one call to the function.




PreviousNext

Related