The Array object is used to store multiple values in a single variable.
Create an array
Create an array, assign values to it, and write the values to the output.
(You can find more examples at the bottom of this page)
For a complete reference of all the properties and methods that can be used with the Array object, go to our complete Array object reference.
The reference contains a brief description and examples of use for each property and method!
An array is a special variable, which can hold more than one value, at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The best solution here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by referring to the array name.
Each element in the array has its own ID so that it can be easily accessed.
An array can be defined in three ways.
The following code creates an Array object called myCars:
1:
2:
3:
Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
will result in the following output:
To modify a value in an existing array, just add a new value to the array with a specified index number:
Now, the following code line:
will result in the following output:
Join all elements of an array into a string - join()
Remove the last element of an array - pop()
Add new elements to the end of an array - push()
Reverse the order of the elements in an array - reverse()
Remove the first element of an array - shift()
Select elements from an array - slice()
Sort an array (alphabetically and ascending) - sort()
Sort numbers (numerically and ascending) - sort()
Sort numbers (numerically and descending) - sort()
Add an element to position 2 in an array - splice()
Convert an array to a string - toString()
Add new elements to the beginning of an array - unshift()
| WEB HOSTING |
|---|
| Best Web Hosting |
| PHP MySQL Hosting |
| Best Hosting Coupons |
| UK Reseller Hosting |
| Cloud Hosting |
| Top Web Hosting |
| $7.95/mo SEO Hosting |
| Premium Website Design |
| WEB BUILDING |
|---|
| Download XML Editor |
| FREE Website BUILDER |
| Free Website Templates Free CSS Templates |
| Make Your Own Website |
| W3SCHOOLS EXAMS |
|---|
|
Get Certified in: HTML, CSS, JavaScript, XML, PHP, and ASP |
| W3SCHOOLS BOOKS |
|---|
|
New Books: HTML, CSS JavaScript, and Ajax |
| STATISTICS |
|---|
|
Browser Statistics Browser OS Browser Display |
| SHARE THIS PAGE |
|---|