JavaScript Array object

Basic concepts of JavaScript arrays

An array is a collection of a series of values, that is, it can be regarded as multiple variables represented by a total variable. 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...)

Explanation: Array(3) means creating an array with 3 elements, but in fact the array The number of elements is still variable. The following are commonly used examples of creating 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);


Array elements are just like variables and can be anything JavaScript supports, or even an array, as shown in the example above.

JavaScript also supports invisible declaration to create an array:

var array_4 = ['a',10.5,true];

But It should be noted that array_4 and array_3 are not equal, alert(array_3==array_4) will output false.


Operations of array elements

Read elements The value

array contains multiple array elements. Access to the array elements is done through subscripts. Note that the subscripts start counting from 0:

var array_3 = new Array('a',10.5,true);
alert( array_3[1] ); // Output: 10.5

Modify the value of the element

##var array_3 = new Array('a',10.5,true);array_3[1] = 20; //Assign Give new value to element
alert( array_3[1] ); // Output: 20


Add element

JavaScript supports the following new style of adding new elements directly after the array:

var array_3 = new Array('a',10.5,true);array_3[3] = 'new value'; // Assign new value to element
alert( array_3[3] ); // Pop-up prompt window output: 20

Add more array elements Methods can also be referenced:

JavaScript push method: Add one or more elements to the end of the array

JavaScript unshift method: Add one or more elements to the beginning of the array

JavaScript splice method: Insert, delete or replace elements of an array

Delete elements

To delete array elements, please refer to the following:

JavaScript pop method: Add one or more elements to the end of the array

JavaScript shift method: Add one or more elements to the beginning of the array

JavaScript splice method: Insert, delete or replace the array Element

Tip: Assigning the array element to null can only clear the element's value but not delete the element.

Example:

    php中文网(php.cn) 


Continuing Learning
||
php中文网(php.cn)
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!