The basic concept of JavaScript Array array is a collection of values, which can be seen as multiple variables expressed by a total variable. The array contains 0 or more array elements. Create an array using the new keyword in JavaScript. Syntax: // create an empty array: newArray () // create an array of num elements: newArray (
Basic concepts of JavaScript Array
An array is a set of values, which can be seen as multiple variables expressed by a total variable. The array contains 0 or more array elements.
Create an array
Use the new keyword in JavaScript to create an array. The syntax is as follows:
// Create an empty array:
New Array ()
// Create an array of num elements:
New Array (num)
// Directly create an array with element values:
New Array (element0, element1, element2 ...)
Note: Array (3) indicates an Array with three elements to be created, but the number of elements in the Array is actually variable. The following are examples of commonly used Arrays:
Var array_1 = new Array ();
Array_1 [0] = 'a ';
Array_1 [1] = 10.5;
Array_1 [2] = true;
Var array_2 = new Array (3)
Array_2 [0] = {x: 10, y: 15 };
Array_2 [1] = document. getElementById ("article ");
Array_2 [2] = new Array ();
Var array_3 = new Array ('A', 10.5, true );
The array element is like a variable. It can be anything supported by JavaScript, or even an array, as shown in the preceding example.
JavaScript also supports the creation of an array through implicit declaration:
Vararray_4 = ['A', 10.5, true];
Note that array_4 and array_3 are not equal, and alert (array_3 = array_4) Outputs false.
Operations on array elements
Read element value
The array contains multiple array elements. The access to the array elements is done by subscript. Note that the subscript starts counting from 0:
Var array_3 = new Array ('A', 10.5, true );
Alert (array_3 [1]); // output: 10.5
Modify element value
Var array_3 = new Array ('A', 10.5, true );
Array_3 [1] = 20; // assign a new value to the element
Alert (array_3 [1]); // output: 20
To replace one or more elements in an array, see JavaScript splice: insert, delete, or replace elements in an array.
Add Element
JavaScript supports the following new rules to add new elements directly behind the array:
Var array_3 = new Array ('A', 10.5, true );
Array_3 [3] = 'new value'; // assign a new value to the element.
Alert (array_3 [3]); // output in the pop-up window: 20
For more methods to add array elements, refer:
Delete Element
To delete an array element, see the following:
Tip: assign an array element to null. You can only clear the element value, but cannot delete it.