Home > Web Front-end > JS Tutorial > body text

JS—array

巴扎黑
Release: 2016-12-06 11:20:02
Original
1437 people have browsed it

Array (Array object)
Array is a kind of object. An array is an ordered collection of values. Each value is called an element (can be of any type), and each element has a position in the array, represented by a number, called an index (0-232-2).
1. Create an array
1. Use array literals (direct quantities)
var empty=[];//Empty array
var misc=[1.1,true,"a",[1,{x:1,y: 2}]];//The element types are different
var count=[1,,2];//There are 3 elements, and the omitted value in the middle is undefined
var undefs=[,,];//There are 2 elements , but it will also be parsed into 3, so don’t do this
2. Call the constructor Array()
var a=new Array();//Without parameters, it is equivalent to an empty array
var a=new Array(10); //Specify an array with a length of 10
var a=new Array(10, 4, "hhhh"); //Specify the array element, but it is not better to use the literal method directly
2. Reading and writing of array elements
var arr =[1,2,3,4,5];
arr[1];//The first element of the array - 2
arr[5]=6;//Dynamicly add (no need to redefine) the first element Five elements - 6
delete arr[0]; The first element is deleted, but the array length is still 6 and the first element is undefined
3. Sparse array
A sparse array contains elements starting from 0 Discontinuously indexed array. Generally, the length attribute value is larger than the actual number of elements
var arr1=[undefined];
var arr2=new Array(1);//Equal to var arr2=[,];
0 in arr1;// Return true, index There is an element at 0
0 in arr2; // Return false, there is no element at index 0
4. Array attribute
length: arr1.length;
5. Array traversal
for(var i=0;i6. Multi-dimensional array
arr[][]

//Create a multi-dimensional array
var table=new Array(10);//The table has 10 rows
for(var i=0;i< table.length;i++)
table[i]=new Array(10); //Each row has 10 columns
//Initialize the array
for(var row=0;rowfor( var col=0;coltable[row][col]=row*col;
}
}
//Use multi-dimensional array calculation
var product=table[5][7]; //The result is 35
Seven. Array method




1.join()
Convert all elements in the array into strings and connect them together, return a string, you can specify a delimiter to separate the elements, if not specified the default Separate with ",".
var arr=[1,2,3];
arr.join();//”1,2,3”
arr.join(“_”);//”1_2_3”


2.reverse( )
Reverse the order of the elements in the array and return the reversed array, and the original array is modified
var arr=[1,2,3];
arr.reverse();//[3,2,1]




3.sort()
Sort the elements in the array and return the sorted array, and the original array is modified. If the element is undefined, it will be sorted to the end
arr=["a","c","b"];
arr.sort();//["a","b","c"] If this method is called without parameters, the elements are sorted in alphabetical order

arr=[13,24,51,3];
arr.sort() ;//[13,24,3,51] Convert the number to The strings are then compared, and the first digit of each number is sorted from small to large

arr.sort(function(a,b){
return a-b;//According to the order, [3,13,24,51]
})

arr.sort(function(a,b){
return b-a;//Reverse order, [51,24,13,3]
})



4.concat()
Merge arrays, the original array is not Modify

var arr=[1,2,3];
arr.concat(4,5);//[1,2,3,4,5]
arr.concat([4,5],6) ;//When the [1,2,3,4,5,6] parameter is an array, the array will be flattened
arr.concat(4,[5,[6,7]]);//[1,2, 3,4,5,[6,7]] When the parameter is an array, the array element is still an array, the array will not be flattened twice




5.slice()
Returns a fragment or subarray of the specified array, Its two parameters specify the beginning and end positions of the segment respectively, which are generally left-closed and right-open intervals. The original array has not been modified

var arr=[1,2,3,4,5];
arr.slice(1, 3);//[2,3]
arr.slice(1);//[2,3,4,5] has only one parameter, this parameter is regarded as the starting position, and the end position is the end of the array
arr. slice(1,-1);//[2,3,4] Negative numbers represent the position relative to the last element in the array, -1 represents the element 5
arr.slice(-4,-3);//[ 2]




6.splice()
Insert or delete elements in the array, the original array is modified

var arr=[1,2,3,4,5]
arr.splice(2);/ /[3,4,5] deletes the elements from the second position to the end

arr.splice(2,2);//[3,4] The second parameter indicates the number of deleted elements, that is, from Delete two elements starting from the second position

arr.splice(1,1,"a","b"); //[2] Delete one element starting from the first position and insert "a" and "a" here "b"
arr;//[1, "a","b",3,4,5]



7.push() and pop()
Using the array as a stack, the original array is modified.
push() adds one or more elements to the end of the array and returns the new length of the array;
pop() deletes the last element of the array, reduces the length of the array and returns the deleted value

var stack=[];
stack. push(1,2);//Return the array length 2
stack.pop();//Return the deleted element 2 at the end



8.unshift() and shift()
unshift() at the head of the array Add one or more elements and return the new length of the array;
shift() deletes the first element of the array and returns the deleted value

var arr=[];
arr.unshift(2);//returns the array length 1
arr.unshift(22);//Returns the array length 2, at this time arr=[22,2]
arr.shift();//Returns the element 22 with the head deleted




9.toString() and toLocaleString()
toString() converts the array to a string, separated by ","
toLocaleString() converts the array to a string, and uses the localization separator

[1,[2,"c"] ].toString()//Return "1,2,c"





8. Array methods in ECMAScript5
ECMAScript5 defines 9 new array methods to traverse, map, filter, detect, simplify and search Array

1.forEach()
Array traversal, the parameter is a function. This function can be called with 3 parameters: the element, the index, and the array itself.

var arr=[1,2,3,4,5];
var sum=0;
arr.forEach(function(value){
sum+=value; //Traverse the array and add each value to sum
});
sum;//15

arr.forEach(function(v,I,a){ //Call this function with 3 parameters: element, index, array itself
a[i]=v+1 ;
})



PS: This method cannot terminate the traversal early like for, so put it in a try block
function foreach(a,f,t){
try{
a.forEach(f ,t);
}catch(e){
if(e==foreach.break)return;
else throw e;
}
}
foreach,break=new Error(“StopIteration”);
                     ​​​​​​​

2. map()
Array mapping, the original array has not been modified

var arr=[1,2,3];
arr.map(function(x){
return x+10;
});//return [11 ,12,13]



3.filter()
Array filtering, the original array is not modified, the returned array is always dense

var arr=[1,2,3,4,5,6,7 ,8,9,10];
arr.filter(function(x,index){
return index%3==0||x>=8;
});//[1,4,7,8, 9,10]

4.every() and some()
Logical judgment of the array, returns true or false, and once the value that should be returned is confirmed, it will stop traversing the array
every() is equivalent to the logical "AND", only Return true only if all elements call the judgment function and return true
some() is equivalent to logical "OR". If at least one element calls the judgment function and return true, return true

var arr=[1,2,3,4 ,5];
arr.every(function(x){
return x<10;
});//true
arr.every(function(x){
return x<3;
});//false

var arr=[1,2,3,4,5];
arr.some(function(x){
return x==3;
});//true
arr.every(function(x) {
return x==10;
});//false

PS: When called on an empty array. every() returns true, some() returns false

5.reduce() and reduceRight()
Use the specified function to combine the array elements to produce a single value, the original array is not modified
reduce() has two parameters, The first is a function that performs the reduction operation. The second optional is the initial value passed to the function. The reduction operation of reduceRight() is from right to left. The rest is the same as reduce().

var arr=[1 ,2,3];
var sum=arr.reduce(function(x,y){
return x+y;
},0);//Return 6, that is, from left to right 0+1=1,1 +2=3, 3+3=6

var sum=arr.reduceRight(function(x,y){
return x+y;
});//Return 6, that is, 3+2= from right to left 5,5+1=6
6.indexOf() and lastIndexOf()
Array retrieval, returns the index of the first element found, if not, returns -1
indexOf() searches from beginning to end
lastIndexOf() starts from Search backward and forward

var arr=[1,2,3,2,1];
arr.indexOf(2);//Find the index of element 2, return 1
arr.indexOf(4);//Find The index of element 4, because it does not exist, returns -1
arr.indexOf(1,1);//Find the index of element 1, start from the first position, return 4
arr.indexOf(1,-3);//Find the index of element 1, start from the third from the bottom, return 4
arr.lastIndexOf(2,-2);//Find the index of element 2, start from the third from the bottom Start searching with two digits, and search from back to front, and return 3


9. Array type
Array.isArray([]);//true
Array.isArray({});//false

[]instanceof Array;//true
({})instanceof Array;//false

({}).toString.apply([])===”[object Array]”;//true

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template