Friday, March 30, 2018

Array Methods


1. pop/push
2. shift/unshift

Things To Remember:

       1. push appends an element to the end.

       2. shift get an element from the beginning

       3. pop takes an element from the end. (remove)


Note:

1. Pop and Push will work with end of the array.

2. Shift and unShift work with starting of the array.



Let see an example for pop,

Below will extract the last element and returns.


let test = ["Apple", "Orange", "Grapes"];

alert( test.pop() ); // remove "Grapes"

alert( test ); // Output is : Apple, Orange


Let see an example for push,

Append the element to the end of the array


let fruit = ["Apple", "Orange"];

fruit.push("Grapes");

alert( fruit ); // Apple, Orange, Grapes


Let see an example for shift,

Extracts the first element of the array and returns it.


let fruitsTest = ["Apple", "Orange", "Pear"];

alert( fruitsTest.shift() ); // remove Apple

alert( fruitsTest ); // Orange, Pear


Let see an example for unshift,


Add the element to the beginning of the array.


let unshiftExample = ["Orange", "Pear"];

unshiftExample.unshift('Apple');

alert( unshiftExample ); // Apple, Orange, Pear


How do you add multiple elements at a single operation?

see the below example,


let fruitsMultiple = ["Apple"];

fruitsMultiple.push("Orange", "Peach");
fruitsMultiple.unshift("Pineapple", "Lemon");

// ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]
alert( fruitsMultiple );









No comments:

Post a Comment