js array some methods

Multidimensional Arrays

js does not support true multi-dimensional arrays. You can use an array of arrays to simulate accessing elements in an array. You can simply use the [] operator twice.
Assume that the variable gf is an array of arrays. The basic elements are the values ​​of each of gf[x] The elements all contain
an array of values ​​code gf[x][y] to access a specific value in the values

Example of making a multiplication table using multidimensional arrays

var t = new Array(10) //The table has 10 rows
 for(var i=0;i<t.length;i++){
 t[i] = new Array(10) // each row has 10 columns
 }//Initialize the array
 for(var row = 0; row<t.length;row++){
for(col = 0;col<t[row].length;col++){
t[row][col] = row*col		
	}
}
//Calculate 5*7 using multidimensional array
var p = t[5][7]
var d = t[6][8] //48
console.log(p) //output 35

 

join() converts all elements in the array into strings and splices them together to return the resulting string

The default is to separate with commas (,)

var arr = new Array(3)
arr[0] = "gf"
arr[1] = "gf"
arr[2] = "gf"
console.log(arr.join())
//gf,gf,gf

 Use the specified . to separate

var arr = new Array(3)
arr[0] = "gf"
arr[1] = "gf"
arr[2] = "gf"
console.log(arr.join('.'))
//gf.gf.gf

 

reverse()

Reverse the order of an array

var a = [1,2,3]
console.log(a.reverse())
//3,2,1

 

sort()

Arrays are sorted alphabetically, the elements are alphabetically sorted, if they are numbers, they are sorted by size

var a = [66,88,3]
console.log(a.sort())
//3,66,88

 

concat()

Concatenate two or more arrays

var a = [1,2,3];
console.log(a.concat(4,5));
//1,2,3,4,5

 

slice()

Returns the selected element from an existing array

var a = [1,2,3,4,5]
console.log(a.slice(0,3))
console.log(a.slice(0,3,6)) 1,2,3 If there are three parameters he only returns the first to second parameters
console.log(a.slice(-3,-2))   3
If there is a negative number, it means the array is in reverse order -1 means the last number in the array
//1,2,3


The two parameters represent the start and end positions, respectively. If there is only one parameter, it will go from the parameter position to the end.

 

pop()

Remove and return the last element of an array

var a = [1,2,3,4,5]
console.log(a.pop())
console.log(a)
//5
//1,2,3,4

 

shift()

Delete the first element of the array and return the first element

var a = [1,2,3,4,5]
console.log(a.shift())
console.log(a)
//1
//2,3,4,5

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326767566&siteId=291194637