Javascript Arrays


JavaScript array basic concepts

An array is a collection of values ​​that can be thought of as a variable with a total number of variables. The array contains zero or more array elements.

Create an array

JavaScript to use the new keyword to create an array, the syntax is as follows:

// Create an empty array:
new Array()
// Create an array of num elements:
new Array(num)
// Create an array with element values ​​directly:
new Array(element0, element1, element2 ...)

Array(3) indicate creation of array with the 3 elements, but in fact the number of elements of the array is still 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);

An array element is just like a variable, and can be anything that JavaScript supports, or even an array, as in the example above.

JavaScript also supports stealth declarations to create an array:

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

Note that array_4 and array_3 are not equal, alert (array_3 == array_4) will output false.


Array element operation

Reads the value of the element

An array contains a number of array elements, access to array elements is done by indexing, and the index is counted from 0:

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

Modifies the value of an element

var array_3 = new Array('a', 10.5, true);
array_3[1] = 20; // assign the new value to the element
alert(array_3[1]); // output: 20

Add element

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

Other methods to add array element :
  • push() : add one or more elements to the end of the array
  • unshift() : Add one or more elements to the beginning of an array
  • splice() : insert, delete or replace the elements of the array

Deletes element

To delete an array element :
  • pop() : add one or more elements to the end of an array
  • shift() : add one or more elements to the beginning of an array
  • splice() : insert, delete or replace the elements of the array

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




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook