The previous words
There are 22 methods in the array. This article divides them into object inheritance methods, array conversion methods, stack and queue methods, array sorting methods, array splicing methods, subarray creation methods, array deletion methods, array position methods, array merge methods and array iteration methods in detail.
Object inheritance method
Array is a special object that inherits the toString(), toLocaleString() and valueOf() methods of the object Object.
【toString()】
toString() method returns a comma-separated string spliced from the string form of each value in the array.
[Note] The return value of this method is the same as the string returned by calling the join() method without any parameters.
[1,2,3].toString();//'1,2,3'['a','b','c'].toString();//'a,b,c'[1,[2,'c']].toString();//'1,2,c'
Since alert() wants to receive string parameters, it will call the toString() method in the background, and will get the same result as the toString() method
alert([1,2,3]);//'1,2,3'
【toLocaleString()】
toLocaleString() is a localized version of the toString() method, which often returns the same value as the toString() method, but it is not always the case. Because, it calls the element, the toLocaleString() method converts each array element into a string
var person1 = {toLocaleString: function(){return 'Nikolaos';},toString: function(){return 'Nikolas';}};var person2 = {toLocaleString: function(){return 'Grigorios';},toString: function(){return 'Greg';}};var people = [person1,person2];console.log(people.toString());//'Nikolas,Greg'console.log(people.toLocaleString());//'Nikolas,Grigorios'If the value of an item in the array is null or undefined, the value is represented as an empty string in the results returned by the toLocaleString() and toString() methods.
var colors = [1,undefined,2,null,3];console.log(colors.toString());//'1,,2,,3'console.log(colors.toLocaleString());//'1,,2,,3'
【valueOf()】
The valueOf() method returns the array object itself
var a = [1, 2, 3];console.log(a.valueOf());// [1, 2, 3]console.log(a.valueOf() instanceof Array);// true
Array conversion method
【join()】
The Array.join() method is an inverse operation of the String.split() method, which splits the string into several blocks to create an array.
The toLocaleString() and toString() methods inherited by arrays will return array items in comma-separated characters by default; the join() method can use different delimiters to build this string. The join() method only receives one parameter, which is used as a delimiter, and then returns a string containing all array items.
If no value is passed to the join() method, use a comma as the separator
var a = [1,2,3];console.log(a.join());//'1,2,3'console.log(a.join(' '));//'1 2 3'console.log(a.join(''));//'123'var b = new Array(10);b.join('-');//'------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------If the parameter of the join() method is undefined, the standard browser returns the string with a comma as the separator, and the IE7-browser returns the string with 'undefined' as the separator.
//The standard browser is '1,2,3'; IE7-the browser is '1undefined2undefined3'var a = [1,2,3];console.log(a.join(undefined));
If the value of an item in the array is null or undefined, the value is represented as an empty string in the result returned by the join() method
var colors = [1,undefined,2,null,3];console.log(colors.join());//'1,,2,,3'
This method can also be used on class array objects
console.log(Array.prototype.join.call('hello', '-'));// "hello"var obj = { 0: 'a', 1: 'b', length: 2 };console.log(Array.prototype.join.call(obj, '-'));// 'ab'[Note] If the object does not have a length attribute, it is not a class array, and the array method cannot be called
var obj = { 0: 'a', 1: 'b' };console.log(typeof Array.prototype.join.call(obj, '-'));//''Stack and queue methods
The push() and pop() methods allow arrays to be used as stacks. The behavior of unshift() and shift() methods is very similar to push() and pop(). The difference is that the former inserts and deletes elements at the head of the array rather than at the tail.
The stack is a LIFO (Last-First-Out, later-in-first-out) data structure, that is, the latest added item is removed at the earliest. The insertion (called pushing) and removal (called pop-up) of items in the stack only happens at one location - the top of the stack. JavaScript provides push() and pop() methods specifically for arrays to achieve stack-like behavior
The access rule for queue data structure is FIFO (first-in-first-out, first-in, first-out). The queue adds items at the end of the list and removes items from the front end of the list. Using the shift() and push() methods in combination, you can use arrays like queues
【push()】
The push() method can receive any number of parameters, add them one by one to the end of the array, and return the length of the modified array. So, the array will change the original array
var a = [];console.log(a,a.push(1));//[1] 1console.log(a,a.push('a'));//[1,'a'] 2console.log(a,a.push(true, {}));//[1,'a',true,{}] 4console.log(a,a.push([5,6]));//[1,'a',true,{},[5,6]] 5If you need to merge two arrays, you can use the apply method
var a = [1, 2, 3];var b = [4, 5, 6];console.log(a,Array.prototype.push.apply(a,b));//[1,2,3,4,5,6] 6
[Note] If you use the call method, the array b will be regarded as a parameter as a whole
var a = [1, 2, 3];var b = [4, 5, 6];console.log(a,Array.prototype.push.call(a,b));//[1,2,3,[4,5,6]] 4
Push() method can also add elements to the object, and the added object becomes an array object, that is, the index of the corresponding array of the key of the newly added element, and the object has a length attribute
var obj = {a: 1};console.log(obj,[].push.call(obj, 2));// {a:1, 0:2, length: 1}console.log(obj,[].push.call(obj, [3]));// {a:1, 0:2, 1:[3], length: 2}【pop()】
The pop() method removes the last item from the end of the array, reduces the length value of the array, and returns the removed item. So, the array will change the original array
var a = ['a', 'b', 'c'];console.log(a,a.pop()); // ['a', 'b'] 'c'
Using pop() method for empty arrays will not report an error, but will return undefined
var a = [];console.log(a,a.pop()); // [] undefined
【shift()】
The shift() method removes the first item in the array and returns the item, while the length of the array is reduced by 1. So, the array will change the original array
var a = ['a', 'b', 'c'];console.log(a,a.shift());//['b', 'c'] 'a'
Use shift() method for empty arrays, and no error will be reported, but will return undefined
var a = [];console.log(a,a.shift());// [] undefined
【unshift()】
The unshift() method adds any item in the front end of the array and returns the new array length. So, the array will change the original array
var a = ['a', 'b', 'c'];console.log(a,a.unshift('x')); //['x', 'a', 'b', 'c'] 4When unshift() is called with multiple parameters, the parameters are inserted at one time rather than one at a time. This means that the order of the elements inserted in the final array is consistent with their order in the parameter list
var a = ['a', 'b', 'c'];console.log(a,a.unshift('x','y','z')); //['x','y','z','a', 'b', 'c'] 6[Note] In IE7-browser, the unshift() method returns always undefined
//In standard browser, return [1] 1; and in IE7-browser, return [1] undefinedvar a = [];console.log(a,a.unshift(1));
Array sorting method
There are two methods in the array that can be used to reorder directly: reverse() and sort()
【reverse()】
Reverse() method is used to reverse the order of the array and return the sorted array; and the original array order has also changed.
var array = [1,2,4,3,5];console.log(array,array.reverse());//[5,3,4,2,1] [5,3,4,2,1]var array = ['str',true,3];console.log(array,array.reverse());//[3,true,'str'] [3,true,'str']
【sort()】
By default, the sort() method arranges array items in ascending order of strings. The sort method will call the toString() method of each array item, and then compare the resulting string sort to return the sorted array, and the original array order also changes.
var array = [1,2,4,3,5];console.log(array,array.sort());//[1,2,3,4,5] [1,2,3,4,5]var array = ['3str',3,2,'2'];console.log(array,array.sort());//[2, "2", 3, "3str"]var array = [1,5,10,50];console.log(array,array.sort());//[1, 10, 5, 50]
If the array contains undefined elements, they are placed at the end of the array
var array = ['3',3,undefined,2,'2'];console.log(array,array.sort());//["2", 2, "3", 3, undefined] ["2", 2, "3", 3, undefined]
The sort() method can accept a comparison function as an argument to specify which value is preceded by which value. The comparison function receives two parameters, returns a negative number if the first parameter should be before the second parameter, returns 0 if the two parameters are equal, and returns a positive number if the first parameter should be after the second parameter
function compare(value1,value2){if(value1 < value2){return -1;}else if(value1 > value2){return 1;}else{return 0;}}var array = ['5px',50,1,10];//When the number is larger than the string, the string '5px' will be converted to NaN, and the result is false seconsole.log(array.sort(compare));//["5px",1, 10, 50]For numerical types or valueOf() method, the comparison function can simplify the object type of the numerical type.
function compare(value1,value2){return value1 - value2;}var array = ['5px',50,1,10];console.log(array.sort(compare));//["5px",1,10,50]var array = [5,50,1,10];console.log(array.sort(compare));//[1,5,10,50]If an array of strings is performed insensitive alphabet sorting, the comparison function first converts the parameters to lowercase strings and then starts the comparison
a = ['ant','Bug','cat','Dog'];a.sort();//['Bug','Dog','ant','cat'];a.sort(function(s,t){var a = s.toLowerCase();var b = t.toLowerCase();if(a < b)return -1;if(a > b)return 1;return 0;});//['ant','bug','cat','dog']【tips】Create a random array using the sort() method
function compare(){return Math.random() - 0.5;}var array = [1,2,3,4,5];console.log(array.sort(compare));//[2,1,5,4,3]Array stitching method
【concat()】
The concat() method creates a new array based on all items in the current array. First create a copy of the current array, then add the received parameters to the end of the copy, and finally returns the newly built array. Therefore, concat() does not affect the original array
If the parameter is not passed to the concat() method, it simply copies the current array; if the parameter is one or more arrays, the method adds each item in these arrays to the result array; if the passed value is not an array, these values are simply added to the end of the result array
var numbers = [1,2];console.log(numbers,numbers.concat(3,4));//[1,2] [1,2,3,4]console.log(numbers,numbers.concat([5,4,3],[3,4,5],1,2));//[1,2] [1,2,5,4,3,3,4,5,1,2]console.log(numbers,numbers.concat(4,[5,[6,7]]));//[1,2] [1,2,4,5,[6,7]]
If no parameters are provided, the concat() method returns a shallow copy of the current array. The so-called "shallow copy" means that if the array member includes a compound type value (such as an object), the new array copying a reference to the value.
//This method actually only copies the first dimension of the array. The first dimension of the array stores the reference of the second dimension, and the second dimension actually stores their content var numbers = [1,2];var newNumbers = numbers.concat();console.log(numbers,newNumbers);//[1,2] [1,2]numbers[0] = 0;console.log(numbers,newNumbers);//[0,2] [1,2]var numbers = [[1,2]];var newNumbers = numbers.concat();console.log(numbers,newNumbers);//[[1,2]] [[1,2]]numbers[0][0] = 0;console.log(numbers,newNumbers);//[[0,2]] [[0,2]]
The concat() method can also be used to merge objects into arrays, but it must be done with the call() method.
var newArray = Array.prototype.concat.call({ a: 1 }, { b: 2 })console.log(newArray);// [{ a: 1 }, { b: 2 }]console.log(newArray[0].a);//1Create subarray method
【slice()】
The slice() method creates a new array based on one or more items in the current array, accepts one or two parameters, that is, to return the start and end positions of the item, and finally return the new array, so slice() does not affect the original array
The slice(start, end) method requires two parameters start and end, which returns a subarray in this array from the start position to (but does not contain) end position; if end is undefined or does not exist, it returns all items from the start position to the end of the array
If start is a negative number, start = max(length + start,0)
If end is a negative number, end = max(length + end,0)
Start and end cannot swap positions
If there are no parameters, return to the original array
var numbers = [1,2,3,4,5];console.log(numbers.slice(2));//[3,4,5]console.log(numbers.slice(2,undefined));//[3,4,5]console.log(numbers.slice(2,3));//[3]console.log(numbers.slice(2,1));//[]console.log(numbers.slice(-3));//-3+5=2 -> [3,4,5]console.log(numbers.slice(-8));//max(5 + -8,0)=0 -> [1,2,3,4,5]console.log(numbers.slice(0,-3));//-3+5=2 -> [1,2]console.log(numbers.slice(-2,-1));//-2+5=3;-1+5=4; -> [4]
If no parameters are provided, the slice() method returns a shallow copy of the current array
//This method actually only copies the first dimension of the array. The first dimension of the array stores the reference of the second dimension, and the second dimension actually stores their content var numbers = [1,2];var newNumbers = numbers.slice();console.log(numbers,newNumbers);//[1,2] [1,2]numbers[0] = 0;console.log(numbers,newNumbers);//[0,2] [1,2]var numbers = [[1,2]];var newNumbers = numbers.slice();console.log(numbers,newNumbers);//[[1,2]] [[1,2]]numbers[0][0] = 0;console.log(numbers,newNumbers);//[[0,2]] [[0,2]]
The slice() method involves implicit type conversion of Number() transformation function. When start is converted to NaN, it is equivalent to start = 0; when end is converted to NaN (except end is undefined), an empty array is output
var numbers = [1,2,3,4,5];console.log(numbers.slice(NaN));//[1,2,3,4,5]console.log(numbers.slice(0,NaN));//[]console.log(numbers.slice(true,[3]));//[2,3]console.log(numbers.slice(null,undefined));//[1,2,3,4,5]console.log(numbers.slice({}));//[1,2,3,4,5]console.log(numbers.slice('2',[5]));//[3,4,5]You can use the slice() method to turn the class array object into a real array
var arr = Array.prototype.slice.call(arrayLike);Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })// ['a', 'b']Array.prototype.slice.call(document.querySelectorAll("div"));Array.prototype.slice.call(arguments);Array deletion method
【splice()】
splice() and slice() have very similar names, but their functions are essentially different. The splice() method is used to delete part of the original array and can add new array members at the deleted location. This method will change the original array.
splice() returns an array composed of deleted elements, or an empty array if no deleted elements are returned.
The first parameter of splice() start specifies the start position for insertion or deletion. If start is a negative number, start = max(length + start,0); if start is NaN, it is equivalent to start = 0
If only one element is provided, it is equivalent to splitting the original array into two arrays at the specified location
var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice());// [1,2,3,4,5,6,7,8] []var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(4));// [1,2,3,4] [5,6,7,8]var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(-4));//-4+8=4; [1,2,3,4] [5,6,7,8]var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(-9));//max(-9+8,0)=0 [] [1,2,3,4,5,6,7,8]var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(NaN));//[] [1,2,3,4,5,6,7,8]
The second parameter number specifies the number of elements that should be deleted from the array. If the second parameter is omitted, all elements from the start point to the end of the array will be deleted. If number is negative or NaN or undefined, number=0, so the element is not deleted
var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(0,2));// [3,4,5,6,7,8] [1,2]var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(10,2));// [1,2,3,4,5,6,7,8] []var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(1,100));// [1] [2,3,4,5,6,7,8] var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(1,-5));//[1,2,3,4,5,6,7,8] []var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(1,NaN));//[1,2,3,4,5,6,7,8] []var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(1,undefined));//[1,2,3,4,5,6,7,8] []var a = [1,2,3,4,5,6,7,8];console.log(a,a.splice(1,undefined));//[1,2,3,4,5,6,7,8] []
If there are more parameters later, it means that these are the new elements to be inserted into the array
var a = [1,2,3,4,5];console.log(a,a.splice(2,0,'a','b'));//[1,2,'a','b',3,4,5] []console.log(a,a.splice(2,2,[1,2],3));//[1,2,[1,2],3,3,4,5] ['a','b']
Array position method
ES5 adds two position methods to array instances: indexOf() and lastIndexOf()
【indexOf()】
IndexOf(search, start) method receives two parameters search and start, returning the location where the search first appears, and if it is not found, it returns -1
The search parameter indicates the item to be searched; use the strict equality operator (===) for comparison
var arr = [1,2,3,'1','2','3'];console.log(arr.indexOf('2'));//4console.log(arr.indexOf(3));//2console.log(arr.indexOf(0));//-1The start parameter indicates the start position of the search. This method implicitly calls the Number() transformation function to convert start non-numeric values (except undefined) into numbers. If this parameter is ignored or if the parameter is undefined or NaN, start = 0
var arr = ['a','b','c','d','e','a','b'];console.log(arr.indexOf('a',undefined));//0console.log(arr.indexOf('a',NaN));//0console.log(arr.indexOf('a',1));//5console.log(arr.indexOf('a',true));//5console.log(arr.indexOf('a',-1));//max(0,-1+7)=6; -1console.log(arr.indexOf('a',-5));//max(0,-5+7)=2; 5console.log(arr.indexOf('a',-50));//max(0,-50+7)=0; 0 var person = {name: 'Nicholas'};var people = [{name: 'Nicholas'}];var morePeople = [person];alert(people.indexOf(person));//-1, because although person and people[0] have the same values, they are two references alert(morePeople.indexOf(person));//0, because person and morepeople[0] are the same reference alert(morePeople.indexOf({name: 'Nicholas'}));//-1, because they are not the same referencecompatible writing method of indexOf() method
if (typeof Array.prototype.indexOf != "function") {Array.prototype.indexOf = function (searchElement, fromIndex) {var index = -1;fromIndex = fromIndex * 1 || 0;for (var k = 0, length = this.length; k < length; k++) {if (k >= fromIndex && this[k] === searchElement) {index = k;break;}}return index;};}【lastIndexOf()】
Unlike indexOf(), lastIndexOf() looks from right to left
The lastIndexOf(search, start) method receives two parameters search and start, returning the location where the search first appears, and if it is not found, it returns -1
The search parameter indicates the item to be searched; use the strict equality operator (===) for comparison
var arr = [1,2,3,'1','2','3'];console.log(arr.lastIndexOf('2'));//4console.log(arr.lastIndexOf(3));//2console.log(arr.lastIndexOf(0));//-1start means the start position of the search, which implicitly calls the Number() transformation function to convert start non-numeric values (except undefined) into numbers. If this parameter is ignored or if the parameter is undefined or NaN, start = 0
Unlike the lastIndexOf() method of a string, when the search method is a negative number, search = max(0, length+search)
var arr = ['a','b','c','d','e','a','b'];console.log(arr.lastIndexOf('b'));//6console.log(arr.lastIndexOf('b',undefined));//-1console.log(arr.lastIndexOf('a',undefined));//0console.log(arr.lastIndexOf('b',NaN));//-1console.log(arr.lastIndexOf('b',1));//1console.log(arr.lastIndexOf('b',-1));//max(0,-1+7)=6; 6console.log(arr.lastIndexOf('b',-5));//max(0,-5+7)=2; 1console.log(arr.lastIndexOf('b',-50));//max(0,-50+7)=0; -1【tips】Return all index values of items that meet the criteria
All matching items can be found by looping to call indexOf() or lastIndexOf()
function allIndexOf(array,value){var result = [];var pos = array.indexOf(value);if(pos === -1){return -1;}while(pos > -1){result.push(pos);pos = array.indexOf(value,pos+1);}return result;}var array = [1,2,3,3,2,1];console.log(allIndexOf(array,1));//[0,5]Compatible writing method of lastIndexOf() method
if (typeof Array.prototype.lastIndexOf != "function") {Array.prototype.lastIndexOf = function (searchElement, fromIndex) {var index = -1, length = this.length;fromIndex = fromIndex * 1 || length - 1;for (var k = length - 1; k > -1; k-=1) {if (k <= fromIndex && this[k] === searchElement) {index = k;break;}}return index;};}Array merge method
The array merging methods include reduce() and reduceRight() methods. They use the specified function to combine array elements to generate a single value. This is a common operation in functional programming, also known as "injection" and "collapse"
【reduce()】
The reduce() method requires two parameters. The first is a function that performs simplified operations. The task of simplifying functions is to use some method to combine or subtract two values into one value and return the simplified value.
The simplified function accepts four parameters, namely:
【1】Initial variable, defaults to the first element value of the array. The return value after the first execution of the function is used as the initial variable for the second execution of the function, and so on
【2】The current variable, if the second parameter is specified, the variable is the value of the first element of the array, otherwise, the value of the second element is the value of the second element.
【3】The index of the elements corresponding to the current variable in the array (starting from 0)
【4】Original array object
Among these four parameters of the simplified function, only the first two are required, while the last two are optional.
values.reduce(function(prev, cur, index, array){//todo});The second (optional) parameter of the reduce() method is an initial value passed to the function
var a = [1,2,3,4,5];var sum = a.reduce(function(x,y){return x+y},0);//Sum of array var product = a.reduce(function(x,y){return x*y},1);//Finding product of array var max = a.reduce(function(x,y){return (x>y)?x:y;});//Finding maximum value[1, 2, 3, 4, 5].reduce(function(prev, cur){console.log(prev, cur)return prev+ cur;});// 1 2// 3 3// 6 4// 10 5// Last result: 15[1, 2, 3, 4, 5].reduce(function(prev, cur){console.log(prev, cur);return prev + cur;},0);// 0 1// 1 2// 3 3// 6 4// 10 5// Last result: 15[Note] The return result type of the reduce() method is the same as the initial value passed in
[1, 2, 3, 4, 5].reduce(function(prev, cur){console.log(prev.sum, cur);prev.sum = prev.sum + cur;return prev;},{sum:0});//0 1//1 2//3 3//6 4//10 5//Object {sum: 15}Using reduce() method, you can write a sum method for sum of arrays
Array.prototype.sum = function (){return this.reduce(function (prev, cur){return prev + cur;})};[3,4,5,6,10].sum();// 28Since the reduce method processes each element in sequence, it can actually be used to search for an element. For example, find the longest array element
function findLongest(entries) {return entries.reduce(function (prev, cur) {return cur.length > prev.length ? cur : prev;}, '');}console.log(findLongest([1,2,3,'ab',4,'bcd',5,6785,4]));//'bcd'You can use the reduce() method to achieve flattening of two-dimensional arrays
var matrix = [[1, 2],[3, 4],[5, 6]];// 2D array flatten var flatten = matrix.reduce(function (prev, cur) {return prev.concat(cur);});console.log(flatten); // [1, 2, 3, 4, 5, 6]On an empty array, calling reduce() without the initial value parameter will result in a type error exception. If there is only one value when it is called - the array has only one element and no initial value is specified, or there is an empty array and an initial value is specified - reduce() simply returns that value without calling the simplified function
var arr = [];arr.reduce(function(){});//Uncaught TypeError: Reduce of empty array with no initial valuevar arr = [];arr.reduce(function(){},1);//1compatible writing method of reduce() method
if (typeof Array.prototype.reduce != "function") {Array.prototype.reduce = function (callback, initialValue ) {var previous = initialValue, k = 0, length = this.length;if (typeof initialValue === "undefined") {previous = this[0];k = 1;}if (typeof callback === "function") {for (k; k < length; k++) {this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));}}return previous;};}【reduceRight()】
ReduceRight() works the same as reduce(), the difference is that it processes the array from high to low (right to left) according to the array index, rather than from low to high
var values = [1,2,3,4,5];var sum = values.reduceRight(function(prev, cur, index, array){console.log(prev,cur);return prev + cur;});console.log(sum);//5 4//9 3//12 2//14 1//15ReduceRight() method compatible writing method
if (typeof Array.prototype.reduceRight != "function") {Array.prototype.reduceRight = function (callback, initialValue ) {var length = this.length, k = length - 1, previous = initialValue;if (typeof initialValue === "undefined") {previous = this[length - 1];k--;}if (typeof callback === "function") {for (k; k > -1; k-=1) { this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));}}return previous;};}Array iteration method
ECMAScript5 defines 5 iterative methods for arrays. Each method receives two parameters: the function to run on each item and the scope object that (optional) runs the function - affecting the value of this. The functions passed into these methods receive three parameters: the value of the array item, the position of the item in the array, and the array object itself. Depending on the method used, the return value after execution of this function may or may not affect the accessed return value
function(item,index,array){//todo}【map()】
The map() method runs a given function on each item of the array, returning an array composed of the results of each function call
//f is the function called by each element of the array. Its return value becomes the element of the return array; o is an optional this value when f is called array.map(f,o); [1,2,3].map(function(item,index,arr){return item*item});//[1,4,9][1,2,3].map(function(item,index,arr){return item*index});//[0,2,6]The map() method can also accept a second parameter, indicating the object pointed to by this when the callback function is executed
var arr = ['a','b','c'];[1,2].map(function(item,index,arr){return this[item]},arr);//['b','c']When using it in practice, you can use the map() method to facilitate the acquisition of specific attribute values in the object array
var users = [{name:'t1',email:'[email protected]'},{name:'t2',email:'[email protected]'},{name:'t3',email:'[email protected]'}];console.log(users.map(function(item,index,arr){return item.email}));//["[email protected]", "[email protected]", "[email protected]"]Map() method can also be used for class array objects
Array.prototype.map.call('abc',function(item,index,arr){return item.toUpperCase()});//["A", "B", "C"]For sparse arrays, the map() method does not call the function on the sequence number where the element does not actually exist.
var a = [1,,3];console.log(a.map(function(item,index,arr){return item*2;}));//[2, 2: 6]Map() method compatible writing method
if (typeof Array.prototype.map != "function") {Array.prototype.map = function (fn, context) {var arr = [];if (typeof fn === "function") {for (var k = 0, length = this.length; k < length; k++) { arr.push(fn.call(context, this[k], k, this));}}return arr;};}【forEach()】
The forEach() method runs a given function on each item in the array, and this method does not return a value. Essentially the same as iterating over an array for loop. If you need a return value, you usually use the map method
[1,2,3,4].forEach(function(item,index,arr){console.log(item)});//1//2//3//4Similar to the for loop below
var array = [1, 2, 3, 4];for (var k = 0, length = array.length; k < length; k++) {console.log(array[k]);}Use the forEach() method to implement simple addition
var sum = 0;[1, 2, 3, 4].forEach(function (item, index, array) {sum += item;});console.log(sum);//10In addition to accepting a necessary callback function parameter, the second parameter can also accept an optional context parameter (change this pointer in the callback function)
var out = [];[1, 2, 3].forEach(function(elem){this.push(elem * elem);}, out);console.log(out);// [1, 4, 9]The second parameter is very useful for multi-layer this, because multi-layer this is usually pointing inconsistent, you can use the second parameter of the forEach() method to fix this
var obj = {name: 'Zhang San',times: [1, 2, 3],print: function () {//This this points to objconsole.log(this); this.times.forEach(function (n) {//This this points to windowconsole.log(this);});}}; obj.print();var obj = {name: 'Zhang San',times: [1, 2, 3],print: function () {//This this points to objconsole.log(this); this.times.forEach(function (n) {//This this also points to objconsole.log(this);},this);}};obj.print();forEach() loop can be used for class array objects
var str = 'abc';Array.prototype.forEach.call(str, function(item, index, array) {console.log( item + ':' + index);});//a:0//b:1//c:2Unlike for loops, for sparse arrays, the forEach() method does not call the function on the order number where the element does not actually exist.
var a = [1,2,3];delete a[1];for(var i = 0; i < a.length; i++){console.log(a[i]);}//1//undefined//3 a.forEach(function(item,index,arr){console.log(item)});//1//3The forEach() method cannot terminate the traversal before all elements are passed to the called function. That is, there is no corresponding break statement like that used in the for loop. If you want to terminate early, you must put the forEach() method in a try block and throw an exception
for(var i = 0; i < 5; i++){if(i == 2) break;}console.log(i);//2 var a = [1,2,3,4,5];console.log(a.forEach(function(item,index,arr){if(index == 2) break;//Uncaught SyntaxError: Illegal break statement})); var a = [1,2,3,4,5];a.forEach(function(item,index,arr){try{if(item == 2) throw new Error; }catch(e){console.log(item);}});forEach() method compatible writing method
if(typeof Array.prototype.forEach != 'function'){Array.prototype.forEach = function(fn,context){for(var k = 0,length = this.length; k < length; k++){if(typeof fn === 'function' && Object.prototype.hasOwnProperty.call(this,k)){fn.call(context,this[k],k,this);}}}}}【filter()】
The filter() method runs a given function on each item in the array, and returns an array of items that will return true. This method is often used to query all array items that meet the criteria
[1, 2, 3, 4, 5].filter(function (elem) {return (elem > 3);});// [4, 5][0, 1, 'a', false].filter(Boolean);// [1, "a"][1, 2, 3, 4, 5].filter(function (elem, index, arr) {return index % 2 === 0;});// [1, 3, 5]The filter() method can also accept a second parameter, specifying the context object (this object) where the test function is located
var Obj = function () {this.MAX = 3;};var myFilter = function (item) {if (item > this.MAX) {return true;}};var arr = [2, 8, 3, 4, 1, 3, 2, 9];arr.filter(myFilter, new Obj());// [8, 4, 9]filter() will skip missing elements in sparse arrays. Its return array is always dense, so it can compress the gaps in sparse arrays.
var a = [1,2,,,,3,,,4];console.log(a.length);//10var density = a.filter(function(){return true;})console.log(dense,dense.length);//[1,2,3,4] 4If you want to compress vacancies and delete undefined and null elements, you can use the filter() method like this
var a = [1,2,,undefined,,3,,null,,4];console.log(a.length);//10var density = a.filter(function(item){return item!= undefined;})console.log(dense,dense.length);//[1,2,3,4] 4Filter() method compatible writing method
if (typeof Array.prototype.filter != "function") {Array.prototype.filter = function (fn, context) {var arr = [];if (typeof fn === "function") {for (var k = 0, length = this.length; k < length; k++) {fn.call(context, this[k], k, this) && arr.push(this[k]);}}return arr;};}【some()】
The some() method runs a given function on each item in the array, and if the function returns true for either item, it returns true. And if and only if all elements in the value call the decision function returns false, it returns false
a = [1,2,3,4,5];a.some(function(elem, index, arr){return elem%2===0;})//truea.some(isNaN);//falseCalling some() method on an empty array will return false
[].some(function(){});//falseSome() method compatible writing method
if (typeof Array.prototype.some != "function") {Array.prototype.some = function (fn, context) {var passed = false;if (typeof fn === "function") {for (var k = 0, length = this.length; k < length; k++) {if (passed === true) break;passed = !!fn.call(context, this[k], k, this);}}return passed;};}【every()】
Every() method runs a given function on each item in the array. If the function returns true for each item, it returns true; if there is an item that returns false, it returns false
a = [1,2,3,4,5];a.every(function(elem, index, arr){elem < 10;})//truea.every(function(elem, index, arr){return elem%2 ===0;});//falseCalling every() method on an empty array will return true
[].every(function(){});//trueEvery() method compatible writing method
if (typeof Array.prototype.every != "function") {Array.prototype.every = function (fn, context) {var passed = true;if (typeof fn === "function") {for (var k = 0, length = this.length; k < length; k++) {if (passed === false) break;passed = !!fn.call(context, this[k], k, this);}}return passed;};}Summarize
JavaScript array methods are specifically defined as general, so they work correctly not only on real arrays but also on class array objects. Of these 22 methods, all methods except toString() and toLocaleString() are common
There are 7 methods that can change the original array: including four stack and queue methods: unshift(), shift(), push(), and pop(), two array arrangement methods: reverse() and sort(), and array deletion method splice()
The above is the 22 must-learn methods of arrays in JavaScript introduced to you by the editor (recommended). I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!