The topic contains a brief explanation of JavaScript Array and how to create and manipulate JavaScript arrays.
Table of Content
What is an Array
Create a JavaScript Array
1 2 3 4 |
var myArray = [1, 2, 3, 4]; var langNamesArray = ["Java", "PHP", "Wordpress"]; //Arrays in JavaScript can hold multiple types of data, as shown. |
Access an Array Item
On the time accessing an array from a variable we use an array index number. On JavaScript array operation, if you want the last element of an array, use ArrayName.length function and subtract 1 for the last array element.
1 2 3 4 5 6 7 |
var first = langNamesArray[0]; // Java var last = langNamesArray[langNamesArray.<strong><span style="color: #1262db;">length</span></strong> - 1]; // Wordpress |
Add an element at the End of an Array
1 2 3 4 |
var newLength = langNamesArray.<span style="color: #1262db;"><strong>push</strong></span>('Laravel'); // ["Java", "PHP", "Wordpress", "Laravel"] |
Remove last element in Array
For removing operation in an array element, we use an array pop function. Array pop function removes an array element from last of an array.
1 2 3 4 5 |
var last = langNamesArray.<span style="color: #1262db;"><strong>pop</strong></span>(); // remove Laravel (from the end) // ["Java", "PHP", "Wordpress"]; |
Remove from the front of an Array
Using array shift function to remove first element of an array.
1 2 3 4 5 |
var first = langNamesArray.<strong><span style="color: #1262db;">shift</span></strong>(); // remove Java from the front // ["PHP", "Wordpress"]; |
Adding the first element to an Array
For adding the first index element in an array we use array unshift function. Check below array unshift function uses the example :
1 2 3 4 5 |
var newLength = langNamesArray.<span style="color: #1262db;"><strong>unshift</strong></span>('Laravel') // add to the front // ["Laravel", "PHP", "Wordpress"]; |
Find the index of an Array Element
For finding the index of an array element we use array indexOf function with array element or value of array parameter. Check the below example for explanation.
1 2 3 4 5 6 7 |
langNamesArray.push('Laravel'); //["Laravel", "PHP", "Wordpress"] var pos = langNamesArray.<strong>indexOf</strong>('PHP'); // 1 |
Loop in an Array
For getting all elements at once we use a loop in an array. In JavaScript array, we use the forEach loop. In the below example, we print an array element name and its index.
1 2 3 4 5 6 7 8 |
langNamesArray.<span style="color: #1262db;"><strong>forEach</strong></span>(function(item, index, array) { console.log(item, index); }); // Java 0 // PHP 1 // Wordpress 2 |
Also Check:
- DOM | DOCUMENT OBJECT MODEL
- SELECTION IN CSS | CSS ::SELECTION
- 3D LOADER USING CSS
- PERCENTAGE DIFFERENCE CALCULATOR USING JQUERY & PHP
Know more:
https://www.php.net/manual/en/function.array.php
Happy Coding..!
4 thoughts to “JavaScript Array | Array length, push, pop, shift, unshift, IndexOf, forEach”