1. Understand arrays
An array is a collection of certain types of data. The data type can be an integer, a string, or even an object.
Javascript does not support multi-dimensional arrays, but because arrays can contain objects (an array is also an object), arrays can achieve functions similar to multi-dimensional arrays by nesting each other.
1.1 Define array
Declare an array with 10 elements
var a = new Array(10);
At this time, the memory space has been opened for a, containing 10 elements. Use the array name plus [subscript] to call it, for example, a[2]. However, the element has not been initialized at this time, and the call will return undefined.
The following code defines a variable array and assigns values
var a = new Array();
a[0] = 10;
a[1] = "aaa";
a[2] = 12.6;
As mentioned above, objects can be placed in arrays, such as the following code
var a = new Array();
a[0] = true;
a[1] = document.getElementById("text");
a[2] = {x:11, y:22};
a[3] = new Array();
Arrays can be assigned values directly when instantiated, for example
var a = new Array(1, 2, 3, 4, 5);
var b = [1, 2, 3, 4, 5];
Both a and b are arrays, but b uses an implicit declaration to create another instance. At this time, if alert(a==b) is used, false will pop up.
1.2 Multidimensional array
In fact, Javascript does not support multi-dimensional arrays. In asp, you can use dim a(10,3) to define multi-dimensional arrays. In Javascript, if you use var a = new Array(10,3), an error will be reported. But as mentioned before, arrays It can contain objects, so an element in the array can be declared as an array, for example
var a = new Array();
a[0] = new Array();
a[0][0] = 1;
alert(a[0][0]); //Pop up 1
Assign a value when declaring
var a = new Array([1,2,3], [4,5,6], [7,8,9]);
var b = [[1,2,3], [4,5,6], [7,8,9]];
The effect is the same, a uses regular instantiation, b is an implicit declaration, and the result is a multi-dimensional array.
1.3 Array literals
I really don’t know what this is called in Chinese, text array?
Speaking of arrays, we have to talk about Array Literals. Arrays are actually special objects. Objects have unique properties and methods. Values and calls are obtained through object name.property and object.method(), while arrays are obtained through subscripts. Values, Array Literals are very similar to arrays. They are both collections of a certain data type. However, Array Literals is fundamentally an object, and its declaration and call are different from arrays.
var aa = new Object();
aa.x = "cat";
aa.y = "sunny";
alert(aa.x); //pop up cat
Create a simple object. Generally, the call is through aa.x. If it is used as Array literals, alert(aa["x"]) will also pop up cat.
var a = {x:"cat", y:"sunny"};
alert(a["y"]); //pop up sunny
Here is another way to create an object, the result is the same