First time writing a blog. . . A bit square. . .
I am a novice (a real novice), self-study of front-end. Now I will talk about some array operations that I summarized during the learning process. If there are any mistakes, please point them out. Humbly accept.
Reference types are divided into Object types (so-called objects), Array types (arrays discussed in this article), Function types, etc.
So, what does an array do? It seems to me that it is used to save data.
1. Declare an array:
1. Constructor var colors=new Array(); for abbreviation, you can omit new, that is, var colors=Array();
2. Array literal var colors=["black","green","pink"];
2. Read and set the value of the array:
Read: colors[x ];Parameter Here is a brief talk about the usage of length:
colors.length gets the length of the array, which can also be said to be the number of items in the array. If an array has 7 items, but you write colors.length=2, Then the next 5 items will be deleted;
Using the length attribute, you can also add data to the array at the end: colors[colors.length]=for assignment;
4. Operations in the array:
MethodReturn value | Array.push(x,y, z) | |
New array length | ##Array.pop() | Remove the end of the array One item |
Array.shift() | Remove the first item of the array | |
Array.unshift(a,b,c) | Add a,b,c at the front of the array | |
Array.reverse() | Reverse array | |
Array.sort() | Arrange the strings of each item in the array in ascending order | |
Array.concat( a,b,c) | Connect arrays | |
Array.slice(1,n) | Intercept the array, from 1 to n, 1 and n are the index values | |
Array.indexOf(a, start) | Find the location of a, starting from start | |
Array.lastIndexOf(a,atart) | Contrary to indexOf, lastIndexOf searches from the end | |
(val1< -1 (val1> 10
Five. Iteration methods in arrays
1.every() and some():
numbers=[0,1,2,3,4 result=numbers.every( (item>2 numbers=[0,1,2,3,4 result=numbers.some( (item>2
2.filter( ):
This method will return an array composed of items whose result is true;
var result=numbers.map(function(item,index,array){ return item*2; })
var numbers=[1,2,3,4,5];var sum=numbers.reduce(function(prev,cur,index,array){return prev+cur }) alert(sum);
In the previous example, reduce() accepts four parameters, The first parameter is the first item of the array, the second parameter is the second item of the array;
The first time the function is executed, prev is 1, cur is 2, the second time it is executed, prev is 3 (The result of 1+2), cur is 3.
The above is the summary of Array array learning in Js. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!