Method: 1. Use the new operator to call the Array() type function to construct a new array, the syntax is "var a = new Array();"; 2. Use the "[]" array direct quantity, the syntax is " var a = [value list];", the list can be empty or a multi-value list with commas separating the values.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to define/create arrays in JavaScript
There are two ways to define (create or declare) arrays in JavaScript: constructing arrays and arrays directly quantity.
Constructing an array
When you use the new operator to call the Array() type function, you can construct a new array.
Example 1
Call the Array() function directly without passing parameters to create an empty array.
var a = new Array(); //空数组
Example 2
Passing multiple values can create a real array.
var a = new Array(1, true, "string", [1,2], {x:1,y:2}); //实数组
Each parameter specifies the value of an element, and there is no limit on the value type. The order of parameters is also the order of array elements, and the length property value of the array is equal to the number of parameters passed.
Example 3
Pass a numeric parameter to define the length of the array, that is, the number of elements it contains.
var a = new Array(5); //指定长度的数组
The parameter value is equal to the attribute value of the array length, and the default value of each element is undefined.
Example 4
If you pass a parameter with a value of 1, JavaScript will define an array with a length of 1 instead of an array containing one element with a value of 1.
var a = new Array(1); console.log(a[0]);
Array literal
The syntax format of array literal: Contain multiple value lists in square brackets, separated by commas.
Example
The following code uses array literals to define an array.
var a = []; //空数组 var a = [1, true, "0", [1,0], {x:1,y:0}]; //包含具体元素的数组
It is recommended to use array literals to define arrays, because array literals are the easiest and most efficient way to define arrays.
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to create a JavaScript array. For more information, please follow other related articles on the PHP Chinese website!