SoFunction
Updated on 2025-04-06

Introduction to various definition methods and common functions of arrays in javascript


Array definition:
Method 1.

Copy the codeThe code is as follows:

var mycars=new Array()
mycars[0]=""
mycars[1]="Volvo"
mycars[2]="BMW"

Method 2.
Definition and initialization together:

Copy the codeThe code is as follows:
var mycars=new Array("Saab","Volvo","BMW");

or:

Copy the codeThe code is as follows:
var mycars=["Saab","Volvo","BMW"];

JavaScript two-dimensional array, simulated with one-dimensional array:
Method 1.

Copy the codeThe code is as follows:
var   arr   =   new   Array(['a','b','c'],['d','e','f']);

arr[0] returns the first one-dimensional array, arr[0][0] returns the first element 'a' of the first one-dimensional array, the same below.
Method 2.
Copy the codeThe code is as follows:

arr=new   Array();  
for(i=0;i<100;i++) {  
     arr[i]=new   Array(...);  
}

Method 3.
Copy the codeThe code is as follows:

var  arr=new  Array(  
  new   Array(),  
  new   Array(),  
  new   Array()  
);

JavaScript array does not need to set length, it will expand itself, the array name.length returns the number of elements

Common functions for javascript arrays:
toString(): Convert an array into a string
toLocaleString(): Convert an array into a string
join(): convert an array into a string connected with symbols
shift(): move an element in the header of the array out
unshift(): Insert an element at the head of the array
pop(): Delete an element from the end of the array
push(): Add an element to the end of the array
concat(): Add elements to the array
slice(): Returns the part of the array
reverse(): reverse sort the array in reverse
sort(): sort the array
splice(): Insert, delete or replace an array element