Sunday 8 April 2018

Arrays in Javascript


Arrays are used to store multiple values in a single variable.

Example :

var list=["apple","banana","grapes"];

As you can see the above example, values are placed inside the brackets and separated by comma(,)

even you can initialize the empty values

var list=[];

Accessing the items in Array :

       index       values
          0            apple
          1            banana
          2            grapes


 Let say , user want to access the banana item in an array then all i need to do is pass in the index value of the item I am interest in:

var selectedItem=list[1];




Adding Item to an array:


  • push
  • unshift


The push method is called directly on your array and pass the data you want to add it.
The above item will get added to your end of the arrays.

list.push("mango");

result: 

       index       values
          0            apple
          1            banana
          2            grapes
          3            mango


If you want to add the items at the beginning of the list then use the below method
list.unshift("watermelon");

result :
     index          values
          0          watermelon
          1            apple
          2            banana
          3            grapes
          4            mango

Removing items from an array:

to remove the items from an array use pop or shift method,its just the reverse of push or unshift.


var remItem=list.pop();

or 

var remFirstItem=list.unshift();


The pop method will the last item from an array and unshift method is used to remove the first item of an array.

Both the method will remove the item from an array and it will return the values of an array.




No comments:

CSS Selectors

  CSS Selectors In CSS, selectors are patterns used to select the element(s) you want to style There are 3 different types of CSS selectors ...