Inserting Items in JavaScript Array



Hello everyone In this Post I am going to explain the basic about Inserting Items in JavaScript Array.

Adding a Item at the end of Array

In JavaScript Array a Item can be added by using index value suppose we have a array as

var a=[A,B,C];

Note the index of array always starts from 0 so if we want to add any element at the end of the array then we can do so by just

a[3] = ‘D’;

Now our array has 4 item as [A,B,C,D] but what if we do not know the number of item in the array then we may use this

a[a.length] = ‘D’;

.length will give us the number of item in the array.

You may also use this approach which is considered more appropriate

a.push(‘D’);

push method will add the item at the end of array and the advantage of using push() method is that we may add more then one element at the end of array

a.push(‘D’, ‘E’, ‘F’);

Adding a Item at the beginning of Array

if we want to add element at the beginning this can be done with the help of  unshift() method

var a=[A,B,C];

a.unshift(‘A’);

Now our array has 4 item as [A,A,B,C] like push we can pass more on item it will add all the item at the beginning of array

var a=[A,B,C];

a.unshift(‘A’, ‘A’, ‘A’);

Now our array has 6 item as [A,A,A,A,B,C] like push we can pass more on item it will add all the item at the beginning of array

 

Stay tuned for the PHP Magento, WordPress, JavaScript and Magento2 latest tutorial and updates, Hope you enjoyed reading, if you need the professional Magento Development / PHP we can help you, just Click on the Link and send me your requirements.

Please Like the Post on Facebook or Google+.