JavaScript arrays are used to store multiple values in a single variable.
Example
var cars = ["Saab", "Volvo", "BMW"];
What is an array?
Arrays are special variables that can store more than one value at a time.
If you have a list of items (for example, a list of car brands), storing car brands in a single variable should look like this:
var car1 = "Saab"; var car2 = "Volvo"; var car3 = "BMW";
But what if you want to traverse all the cars and find a specific value? What if it wasn't three car brands but three hundred?
The solution is arrays!
Arrays can store many values with a single name, and they can also be accessed by referencing index numbers.
Create array
Using array text is the easiest way to create JavaScript arrays.
Syntax:
var array-name = [item1, item2, ...];
Spaces and folds are not important. Declarations can span multiple lines:
Example
var cars = [ "Saab", "Volvo", "BMW" ];
Please do not write comma after the last element (such as "BMW",).
There may be cross-browser compatibility issues.
Use the JavaScript keyword new
The following example also creates an array and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
The effect of the above two examples is exactly the same. No need to use new Array().
For the sake of simplicity, readability and execution speed, use the first method (Array Text Method).
Access array elements
We refer to an array element by referencing the index number (subscript).
This statement accesses the value of the first element in cars:
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
Example
var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars[0]; var name = cars[0];
[0] is the first element in the array. [1] is the second. The array index starts at 0.
Access the complete array
With JavaScript, the full array can be accessed by referencing the array name:
Example
var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars;
Arrays are objects
Arrays are special types of objects. Using the typeof operator on arrays in JavaScript returns "object".
However, JavaScript arrays are best described as arrays.
Arrays use numbers to access their "elements". In this case, person[0] returns Bill:
Array:
var person = ["Bill", "Gates", 62];
Objects use names to access their "members". In this case, person.firstName returns Bill:
Participants:
var person = {firstName:"John", lastName:"Doe", age:46};
Array elements can be objects
JavaScript variables can be objects. Arrays are special types of objects.
Because of this, you can store different types of variables in the same array.
You can save objects in arrays. You can save functions in arrays. You can even save arrays in arrays:
myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars;
Array attributes and methods
The true power of JavaScript arrays lies in the attributes and methods of arrays:
Example
var x = cars.length; // length Attribute returns the number of elements var y = cars.sort(); // sort() Methods Sort arrays
We will learn about array methods in the next chapter.
length attribute
The length attribute returns the length of the array (the number of elements in the array).
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length;
The length attribute is always larger than the highest array index (subscript).
Accessing the first array element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"]; var first = fruits[0];
Access the last array element
Example
fruits = ["Banana", "Orange", "Apple", "Mango"]; var last = fruits[fruits.length - 1];
Traversing array elements
The safest way to traverse an array is to use the "for" loop:
Example
var fruits, text, fLen, i; fruits = ["Banana", "Orange", "Apple", "Mango"]; fLen = fruits.length; text = "<ul>"; for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; }
You can also use the Array.foreach() function:
Example
var fruits, text; fruits = ["Banana", "Orange", "Apple", "Mango"]; text = "<ul>"; fruits.forEach(myFunction); text += "</ul>"; function myFunction(value) { text += "<li>" + value + "</li>"; }
Add array elements
The best way to add new elements to an array is to use the push() method:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Lemon"); // towards fruits Add a new element (Lemon)
You can also use the length attribute to add new elements to the array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Lemon"; // towards fruits Add a new element (Lemon)
Warning!
Adding the element with the highest index creates an undefined "hole" in the array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[6] = "Lemon";
Associative array
Many programming elements support named indexed arrays.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support named indexed arrays.
In JavaScript, arrays can only be indexed numerically.
Example
var person = []; person[0] = "Bill"; person[1] = "Gates"; person[2] = 62; var x = person.length; // person.length Return to 3 var y = person[0]; // person[0] Return "Bill"
If you use named indexes, JavaScript will redefine arrays as standard objects.
After that, the methods and attributes of all arrays will produce incorrect results.
Example:
var person = []; person["firstName"] = "Bill"; person["lastName"] = "Gates"; person["age"] = 62; var x = person.length; // person.length Will return to 0 var y = person[0]; // person[0] Will return undefined
Differences between arrays and objects
In JavaScript, arrays are indexed numerically.
In JavaScript, objects use named indexes.
Arrays are special types of objects with digital indexes.
When to use arrays and when to use objects?
- JavaScript does not support associative arrays
- Objects should be used if you want elements to be named strings (text).
- Arrays should be used if you want the element to be named a number.
Avoid new Array()
There is no need to use JavaScript's built-in array constructor, new Array().
Please use [] instead!
The following two different statements create a new empty array called points:
var points = new Array(); // difference var points = []; // excellent
The following two different statements create a new array of six numbers:
var points = new Array(40, 100, 1, 5, 25, 10); // difference var points = [40, 100, 1, 5, 25, 10]; // excellent
new keywords only complicate the code. It also produces some unexpected results:
var points = new Array(40, 100); // Create an array of two elements (40 and 100)
What happens if one of the elements is deleted?
var points = new Array(40); // Create an array of 40 undefined elements!!!
How to recognize arrays
The common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
var fruits = ["Banana", "Orange", "Apple", "Mango"]; typeof fruits; // Return object
The typeof operator returns "object" because JavaScript arrays belong to objects.
Solution 1:
To solve this problem, ECMAScript 5 defines a new method, Array.isArray():
Array.isArray(fruits); // Return true
The problem with this solution is that ECMAScript 5 does not support older browsers.
Solution 2:
Create your own isArray() function to solve this problem:
function isArray(x) { return x.constructor.toString().indexOf("Array") > -1; }
If the parameter is an array, the above function always returns true.
Or, more accurately, if the object prototype contains the word "Array", it returns true.
Solution 3:
If an object is created by a given constructor, the instanceof operator returns true:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits instanceof Array // Return true
Source: www.sysoft.net.cn, plus v:15844800162 for in-depth communication
fruits = ["Banana", "Orange", "Apple", "Mango"]; var first = fruits[0];