1. Before using the methods of arrays, you need to create arrays, which can be created in the following ways:
- Literal Quantity (json)
var arr1 = []; //Create an empty array
var arr2 = [5]; //Create an array with a single element
var arr3 = [5,6,7]; //Create an array with multiple elements
- Constructor Style
var arr1 = new Array(); //Create an empty array
var arr2 = new Array(5); //Create an array with a length of 5 and an empty value
var arr3 = new Array(5,6,7); //Create an array with multiple elements
2. Summary of Array Methods
Method Name | Corresponding Version | function | Is the original array changed |
---|---|---|---|
concat() | ES5- | Merge the array and return the merged data | n |
join() | ES5- | Converts an array to a string and returns it using a delimiter | n |
pop() | ES5- | Delete the last bit and return the deleted data | y |
shift() | ES5- | Delete the first bit and return the deleted data | y |
unshift() | ES5- | Add one or more data in the first place, return the length | y |
push() | ES5- | Add one or more data to the last bit, return length | y |
reverse() | ES5- | Reverse the array and return the result | y |
slice() | ES5- | Intercepts an array of specified locations and returns | n |
sort() | ES5- | Sort (character rule), return results | y |
splice() | ES5- | Deletes the specified location, replaces it, and returns the deleted data | y |
toString() | ES5- | Converts directly to a string and returns | n |
valueOf() | ES5- | Returns the original value of an array object | n |
indexOf() | ES5 | Query and return the index of the data | n |
lastIndexOf() | ES5 | Reverse query and return index of data | n |
forEach() | ES5 | The parameter is a callback function, which traverses all items of the array. The callback function accepts three parameters, value, index, self; forEach does not return a value. | n |
map() | ES5 | Together with forEach, the callback function returns data, forming a new array returned by map | n |
filter() | ES5 | With forEach, the callback function returns a Boolean value, and a new array of true data is returned by filter | n |
every() | ES5 | With forEach, the callback function returns Boolean values, all true, and all true | n |
some() | ES5 | As with forEach, the callback function also returns a Boolean value, as long as one is true and some returns true | n |
reduce() | ES5 | Merge, with forEach, iterates over all items of the array and builds a final value that is returned by reduce | n |
reduceRight() | ES5 | Reverse merge, with forEach, iterates over all items of the array and constructs a final value, which is returned by reduceRight | n |
3. Method Details
1.concat()
Function: Used to connect two or more arrays, this method does not change the existing array, but only returns a copy of the connected array.
Parameters: concat(data1,data2,...); all parameters are optional, data to be merged; when data is an array, data is merged into the original array; when data is specific, it is added directly to the end of the original array; when omitted, a copy of the original array is created.
var arr1 = [1,2,3]
var arr2 = arr1.concat();
console.log(arr1); //[1,2,3]--original array
console.log(arr1 === arr2); //false
console.log(arr2); //[1,2,3] - Copy of the original array
console.log(arr1.concat("hello","world")); //[1,2,3,"hello","world"]
console.log(arr1.concat(["a","b"],[[3,4],{"name":"admin"}])); //[1,2,3,"a","b",[3,4],{"name":"admin"}]
console.log(arr1); //[1,2,3] - original array unchanged
2.join()
Function: Places all elements in an array into a string according to the specified delimiter and returns the string.
Parameter: join(str); optional parameter, default to "," sign, with incoming character as separator.
var arr = [1,2,3];
console.log(arr.join()); //1,2,3
console.log(arr.join("-")); //1-2-3
console.log(arr); //[1,2,3] - original array unchanged
3.pop()
Function: The method deletes and returns the last element of the array.
Parameter: None
var arr = [1,2,3];
console.log(arr.pop()); //3
console.log(arr); //[1,2] - original array change
4.shift()
Function: The method deletes and returns the first element of the array.
Parameter: None
var arr = [1,2,3]
console.log(arr.shift()); //1
console.log(arr); //[2,3] - original array change
5.unshift()
Function: Add one or more elements to the beginning of the array and return the new length.
Parameter: unshift(newData1, newData2,...)
var arr = [1,2,3];
console.log(arr.unshift("hello")); //4
console.log(arr); //['hello', 1,2,3] - original array change
console.log(arr.unshift("a","b")); //6
console.log(arr); //['a','b','hello', 1,2,3] - original array change
6.push()
Function: Add one or more elements to the end of the array and return the new length.
Parameters: push(newData1, newData2,...)
var arr = [1,2,3];
console.log(arr.push("hello")); //4
console.log(arr); //[1,2,3,'hello']--original array change
console.log(arr.push("a","b")); //6
console.log(arr); //[1,2,3,'hello','a','b'] - original array change
7.reverse()
Function: Reverse the order of elements in an array.
Parameter: None
var arr = [1,2,3];
console.log(arr.reverse()); //[3,2,1]
console.log(arr); //[3,2,1] - original array change
8.slice()
Function: Returns selected elements from an existing array.This method receives two parameters slice(start,end), strat is required, indicating from which bit to start; end is optional, indicating to the first bit to end (excluding the end bit), ellipsis is to the last bit; start and end can be negative, and negative numbers indicate from the last bit, such as -1 for the last bit.
Parameter: slice(startIndex, endIndex)
var arr = ["Tom","Jack","Lucy","Lily","May"];
console.log(arr.slice(1,3)); //["Jack","Lucy"]
console.log(arr.slice(1)); //["Jack","Lucy","Lily","May"]
console.log(arr.slice(-4,-1)); //["Jack","Lucy","Lily"]
console.log(arr.slice(-2)); //["Lily","May"]
console.log(arr.slice(1,-2)); //["Jack","Lucy"]
console.log(arr); //["Tom","Jack","Lucy","Lily","May"]---Original array unchanged
9.sort()
Function: Sorts the elements in an array, in ascending order by default.
var arr = [6,1,5,2,3];
console.log(arr.sort()); //[1, 2, 3, 5, 6]
console.log(arr); //[1, 2, 3, 5, 6] - original array change
However, before sorting, the array's toString method is invoked, each element is converted to a character, and then sorted, which is sorted by string sorting, bit-by-bit comparison.
var arr = [6,1024,52,256,369];
console.log(arr.sort()); //[1024, 256, 369, 52, 6]
console.log(arr); //[1024, 256, 369, 52, 6] - original array change
Parameter: sort(callback)
If you need to sort by value, you need to pass parameters.sort(callback), which is a callback function, should have two parameters, compare the two parameters, and return a number (a-b) describing the relative order of the two values.The return values are as follows:
If A is less than b, a value less than 0 is returned.
If a equals b, 0 is returned.
If A is greater than b, a value greater than 0 is returned.
var arr = [6,1024,52,256,369];
console.log(arr.sort(fn)); //[6, 52, 256, 369, 1024]
console.log(arr); //[6, 52, 256, 369, 1024] - original array change
function fn(a,b){
return a-b;
}
10.splice()
Function: Add to, remove from, or replace elements in an array, and then return the deleted/replaced elements.
Parameters: splice(start,num,data1,data2,...); all parameters are optional.
1>When no arguments are passed: no action
var arr = ["Tom","Jack","Lucy","Lily","May"];
console.log(arr.splice()); //[]
console.log(arr); //["Tom","Jack","Lucy","Lily","May"]---No Operation
2>Just pass in start: indicates deletion from data indexed as start until the end of the array
var arr = ["Tom","Jack","Lucy","Lily","May"];
console.log(arr.splice(2)); //["Lucy", "Lily", "May"]
console.log(arr); //["Tom", "Jack"]---Original Array Change
3>Incoming start and num: means delete num from data indexed as start
var arr = ["Tom","Jack","Lucy","Lily","May"];
console.log(arr.splice(2,2)); //["Lucy", "Lily"]
console.log(arr); //["Tom", "Jack", "May"]---Original Array Change
4>Incoming more: means delete from data indexed as start, delete num, and insert the third parameter and all subsequent parameters into the start location
var arr = ["Tom","Jack","Lucy","Lily","May"];
console.log(arr.splice(2,2,"a","b")); //["Lucy", "Lily"]
console.log(arr); //["Tom", "Jack", "a", "b", "May"]---Original Array Change
5>Incoming more: means delete from data indexed as start, delete num, and insert the third parameter and all subsequent parameters into the start location
var arr = ["Tom","Jack","Lucy","Lily","May"];
console.log(arr.splice(2,0,"a","b")); //[]
console.log(arr); //["Tom", "Jack", "a", "b", "Lucy", "Lily", "May"]---Original Array Change
11.toString()
Function: Converts to a string, similar to join() without parameters.This method is called automatically when an implicit type conversion occurs on the data and, if called manually, is converted directly to a string.
Parameter: None
var arr = [1,2,3];
console.log(arr.toString()); //1,2,3
console.log(arr); //[1,2,3] - original array unchanged
12.valueOf()
Function: Returns the original value of an array (usually the array itself), which is usually called in the background by js and does not appear explicitly in the code
Parameter: None
var arr = [1,2,3];
console.log(arr.valueOf()); //[1,2,3]
console.log(arr); //[1,2,3]
//To prove that the returned array is itself
console.log(arr.valueOf() == arr); //true
13.indexOf()
Function: According to the specified data, from left to right, query the position that appears in the array, if there is no specified data, return -1.This method is a query method and will not change the array.
Parameters: indexOf(value, start);value is the data to be queried; start is optional, indicating where to start the query, forward from the end of the array when start is negative; and method returns -1 if the query cannot find the existence of value
var arr = ["h","e","l","l","o"];
console.log(arr.indexOf("l")); //2
console.log(arr.indexOf("l",3)); //3
console.log(arr.indexOf("l",4)); //-1
console.log(arr.indexOf("l",-1)); //-1
console.log(arr.indexOf("l",-3)); //2
14.lastIndexOf()
Function: According to the specified data, from right to left, query the position that appears in the array, if there is no specified data, return -1.This method is a query method and will not change the array.
Parameters: lastIndexOf(value, start);value is the data to be queried; start is optional, indicating where to start the query, forward from the end of the array when start is negative; and method returns -1 if the query cannot find the existence of value
var arr = ["h","e","l","l","o"];
console.log(arr.lastIndexOf("l")); //3
console.log(arr.lastIndexOf("l",3)); //3
console.log(arr.lastIndexOf("l",1)); //-1
console.log(arr.lastIndexOf("l",-3)); //2
console.log(arr.lastIndexOf("l",-4)); //-1
15.forEach()
Function: ES5 new method to traverse arrays, the method does not return a value.The callback function that forEach receives is executed based on each item of the array. By default, the callback function has three parameters: the data of the traversed array, the corresponding index, and the array itself.
Parameters: forEach(callback);callback defaults to three parameters, value, index, self.
var arr = ["Tom","Jack","Lucy","Lily","May"];
var a = arr.forEach(function(value,index,self){
console.log(value + "--" + index + "--" + (arr === self));
})
// The printout is:
// Tom--0--true
// Jack--1--true
// Lucy--2--true
// Lily--3--true
// May--4--true
console.log(a); //Undefined--forEach has no return value
//This method is traversal and does not modify the original array
16.map()
Function: 1. same as forEach function; 2.map's callback function will return the result of execution, and finally map will make up a new array of the returned values of all callback functions.
Parameters: map(callback);callback defaults to three parameters, value, index, self.
//Function 1: same as forEach
var arr = ["Tom","Jack","Lucy","Lily","May"];
var a = arr.map(function(value,index,self){
console.log(value + "--" + index + "--" + (arr === self))
})
// The printout is:
// Tom--0--true
// Jack--1--true
// Lucy--2--true
// Lily--3--true
// May--4--true
//Function 2: The return value of each callback function is returned by a new array of map s
var arr = ["Tom","Jack","Lucy","Lily","May"];
var a = arr.map(function(value,index,self){
return "hi:"+value;
})
console.log(a); //["hi:Tom", "hi:Jack", "hi:Lucy", "hi:Lily", "hi:May"]
console.log(arr); //['Tom','Jack','Lucy','Lily','May'] - original array unchanged
17.filter()
Functions: 1. With the forEach function; 2. The callback function of the filter needs to return a Boolean value, when true, the data of this array is returned to the filter, and finally the filter returns all the callback functions as a new array (this function can be understood as "filtering").
Parameters: filter(callback);callback defaults to three parameters, value, index, self.
//Function 1: same as forEach
var arr = ["Tom","Jack","Lucy","Lily","May"];
var a = arr.filter(function(value,index,self){
console.log(value + "--" + index + "--" + (arr === self))
})
// The printout is:
// Tom--0--true
// Jack--1--true
// Lucy--2--true
// Lily--3--true
// May--4--true
//Function 2: When the return value of the callback function is true, the array value this time is returned to the filter, which is returned by the filter as a new array
var arr = ["Tom","Jack","Lucy","Lily","May"];
var a = arr.filter(function(value,index,self){
return value.length > 3;
})
console.log(a); //["Jack", "Lucy", "Lily"]
console.log(arr); //['Tom','Jack','Lucy','Lily','May'] - original array unchanged
18.every()
Function: Determines whether each item in the array meets a condition, and returns true only if all items meet a condition.
Parameters: every() receives a callback function as a parameter, which requires a return value of every(callback);callback defaults to three parameters, value, index, self.
Function 1: When the return value of the callback function is true, it traverses everything like forEach; if false, it stops execution, and subsequent data stops traversing and stops at the first return false.
//demo1:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
console.log(value + "--" + index + "--" + (arr == self))
})
// The printout is:
// Tom--0--true
//Because there is no return true in the callback function, undefined is returned by default, which is equivalent to returning false
//demo2:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
console.log(value + "--" + index + "--" + (arr == self))
return value.length < 4;
})
// The printout is:
// Tom--0--true
// abc--1--true
// Jack--2--true
//Because when Jack is traversed, the callback function return s false, and Jack has traversed, but later data is no longer traversed
//demo3:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
console.log(value + "--" + index + "--" + (arr == self))
return true;
})
// The printout is:
// Tom--0--true
// abc--1--true
// Jack--2--true
// Lucy--3--true
// Lily--4--true
// May--5--true
//Because the return value of each callback function is true, all the data in the array is traversed, which is equivalent to the forEach function
Function 2: When the return value of each callback function is true, the return value of everyis true. As long as one callback function has a return value of false, the return value of everyis false.
//demo1:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
return value.length > 3;
})
console.log(a); //false
//demo2:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.every(function(value,index,self){
return value.length > 2;
})
console.log(a); //true
19.some()
Function: Determines whether there are items in the array that satisfy the condition, and returns true if only one of them meets the condition.
Parameters: some() receives a callback function as a parameter, which requires a return value, some(callback);callback defaults to three parameters, value, index, self.
Function 1: Because to determine each item in an array, some s returns true whenever a callback function returns true, contrary to every body, when a callback function returns true, the result can be determined, then the execution stops, followed by data that is no longer traversed, and stops at the position of the first return true; when the callback function returns false, it needs toContinue executing backwards until the final result is determined, so all data is traversed, implementing functions similar to forEach, and all.
//demo1:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.some(function(value,index,self){
console.log(value + "--" + index + "--" + (arr == self))
return value.length > 3;
})
// The printout is:
// Tom--0--true
// abc--1--true
// Jack--2--true
//demo2:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.some(function(value,index,self){
console.log(value + "--" + index + "--" + (arr == self))
return true;
})
// The printout is:
// Tom--0--true
//demo3:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.some(function(value,index,self){
console.log(value + "--" + index + "--" + (arr == self))
return false;
})
// The printout is:
// Tom--0--true
// abc--1--true
// Jack--2--true
// Lucy--3--true
// Lily--4--true
// May--5--true
Function 2: Contrary to every where, as long as one callback function returns true, some returns true, all callback functions return false, some returns false
//demo1:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.some(function(value,index,self){
return value.length > 3;
})
console.log(a); //true
//demo2:
var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
var a = arr.some(function(value,index,self){
return value.length > 4;
})
console.log(a); //false
19.reduce()
Function: Start with the first item of the array, iterate through all items of the array one by one, and then build a final return value.
Parameter: reduce() receives one or two parameters: the first is a callback function, which represents a function called on each item of the array; the second (optional) parameter, which is the initial value of the merge, is received by the first parameter on the first execution of the callback function.
reduce(callback,initial);callback defaults to four parameters, prev, now, index, self.
Any value returned by callback will be the first parameter of the next execution.
If the initial parameter is omitted, the first iteration occurs on the second item of the array, so the first parameter of the callback is the first item of the array, and the second parameter is the second item of the array.
//demo1: without omitting the initial parameter, the callback function does not return a value
var arr = [10,20,30,40,50];
arr.reduce(function(prev,now,index,self){
console.log(prev + "--" + now + "--" + index + "--" + (arr == self))
}, 2019)
// The printout is:
// 2019--10--0--true
// undefined--20--1--true
// undefined--30--2--true
// undefined--40--3--true
// undefined--50--4--true
// At this point the callback function does not return, so from the second time on, prev gets undefined
//demo2: omit initial parameter, callback function does not return value
var arr = [10,20,30,40,50];
arr.reduce(function(prev,now,index,self){
console.log(prev + "--" + now + "--" + index + "--" + (arr == self))
})
// The result is: for the first time, the first parameter of the callback function is the first item of the array.The second parameter is the second item of the array
// 10--20--1--true
// undefined--30--2--true
// undefined--40--3--true
// undefined--50--4--true
// At this point the callback function does not return, so from the second time on, prev gets undefined
//demo3: without omitting the initial parameter, the callback function has a return value
var arr = [10,20,30,40,50];
arr.reduce(function(prev,now,index,self){
console.log(prev + "--" + now + "--" + index + "--" + (arr == self));
return "hello";
}, 2019)
// The printout is:
// 2019--10--0--true
// hello--20--1--true
// hello--30--2--true
// hello--40--3--true
// hello--50--4--true
// At this point the callback function has a return, so from the second time on, prev gets the value of the callback function return
//demo4: omit initial parameter, callback function has return value
var arr = [10,20,30,40,50];
arr.reduce(function(prev,now,index,self){
console.log(prev + "--" + now + "--" + index + "--" + (arr == self));
return "hello";
})
// The result is: for the first time, the first parameter of the callback function is the first item of the array.The second parameter is the second item of the array
// 10--20--1--true
// hello--30--2--true
// hello--40--3--true
// hello--50--4--true
// At this point the callback function has a return, so from the second time on, prev gets the value of the callback function return
//demo5: use reduce to calculate the sum of all the data in the array
var arr = [10,20,30,40,50];
var sum = arr.reduce(function(prev,now,index,self){