preface
Recently, I reviewed the array methods in JavaScript. In order to avoid forgetting them and to be able to review them in time, I hereby summarize.
Check Array instanceof & array.isarray ()
Check whether an object is an array. Returns true, not false.
Log ([1,2,3] instanceof Array) //true console.log(array.isarray ([1,2,3])) //trueCopy the code
Conversion methods toString() & toLocalString() & valueOf() & Join ()
ToString () & toLocalString() converts an array to a string, delimiting each entry with a ‘,’.
The console. The log ([1, 2, 3]. The toString ()) / / 1, 2, 3 the console. The log ([1, 2, 3]. ToLocaleString ()) / / 1, 2, 3Copy the code
The valueOf() method returns the array itself.
The console. The log ([1, 2, 3]. The valueOf ()) / / [1, 2, 3]Copy the code
The join() method takes a single argument as a delimiter and returns a string containing all the array items.
The console. The log ([1, 2, 3]. Join (' | ')) / / 1 | 2 | 3Copy the code
Add and remove methods push() & pop() & Shift () & unshift()
Push () takes multiple arguments, adds them to the end of the array one by one, and returns the modified array length.
The console. The log ([1, 2, 3]. Push (4 and 6)) / / 6Copy the code
Pop () removes the last item in the array and returns the removed item.
The console. The log ([1, 2, 3]. The pop ()) / / 3Copy the code
Unshift () takes multiple arguments, adds them to the front of the array one by one, and returns the modified array length.
console.log([1, 2, 3].unshift(-2, -1, 0)) //6
Copy the code
Shift () removes the first item in the array and returns the removed item.
console.log([1, 2, 3].shift()) //1
Copy the code
Resort methods reverse() & sort()
Reverse () returns the reversed array.
console.log([1, 2, 3].reverse()) //[3, 2, 1]
Copy the code
Sort () sort an array that takes a comparison function as an argument to specify ascending or descending order. By default, the sort() method sorts arrays in ascending order, but because by default the sort() method calls the toString() transformation method for each array item and then compares the resulting strings, sorting errors can occur.
console.log([5, 10, 15, 20].sort(function (value1, value2) {
return value1 - value2
})
) //[10, 15, 20, 5]
Copy the code
The above problem is caused by the way of comparing strings in JavaScript. In JavaScript, the comparison between strings is based on the rank first, comparing the ASCII size of each character, including the comparison between numeric strings, so ‘5’>’10’>’15’>’20’.
console.log([1, 5, 10, 15, 20].sort(function (value1, value2) {
return value1 - value2
})
) //[1, 5, 10, 15, 20]
Copy the code
Ascending sort, if parameter 1> parameter 2, returns a positive number, so parameter 1 comes after parameter 2, if parameter 1< parameter 2, returns a negative number, so parameter 1 comes before parameter 2, same with descending sort.
Concat () & slice() & splice()
Concat () can take multiple arguments, either a single string or an array, and concat() can create a new array based on all the items in the current array without changing the original array.
The console. The log ([1, 2, 3]. The concat ((4 and 6))) / / [1, 2, 3, 4, 5, 6]Copy the code
Slice () can take one or two arguments. If there is only one argument, the slice() method returns all items from the specified position to the end of the array. If there are two arguments, the method returns the items between the start and end positions, but does not contain the end positions and does not alter the array.
console.log([1, 2, 3, 4, 5].slice(2)) //[3, 4, 5]
console.log(arr.slice(1, 3)) //[2, 3, 4]
Copy the code
Splice () can receive two or more parameters, the first parameter to delete the first position, the second parameter to want to delete the item number, after the parameters for the insert, this method will always return a contains an array of the item is removed from the original array, if not remove any item, is an empty array, this method changes the original array.
var arr = [1, 2, 3]
console.log([1, 2, 3, 4, 5].splice(2, 2)) //[2, 3]
console.log(arr) //[1]
var arr = [1, 2, 3]
console.log([1, 2, 3].splice(arr.length, 0, [4, 5])) //[]
console.log(arr) //[1, 2, 3, [4, 5]]
Copy the code
One caveat here is that if the argument passed is a non-string, splice() will also insert that argument into the array as a separate item.
Position methods indexOf() & lastIndexOf()
Both methods take two arguments, the item to look for and the index of the starting position of the search. If the item is found, the position of the item in the array is returned, otherwise -1 is returned. Note that the congruence operator (===) is used during the search. The only difference between lastIndexOf() and indexOf() is that this method looks forward from the end of the array.
console.log([1, 2, 3, 1, 2, 3].indexOf(3)) //2
console.log([1, 2, 3, 1, 2, 3].indexOf(3, 3)) //5
console.log([1, 2, 3, 1, 2, 3].indexOf('1')) //-1
console.log([1, 2, 3, 1, 2, 3].lastIndexOf(3)) //5
console.log([1, 2, 3, 1, 2, 3].lastIndexOf(3, 3)) //2
console.log([1, 2, 3, 1, 2, 3].lastIndexOf('1')) //-1
Copy the code
Iterative methods some() & every() & filter() & forEach() & map()
Some () runs the given function on each item in the array, and returns true if any item in the function returns true.
console.log([1, 2, 3, 4, 5].some(function (item, index, array) {
return item > 3
})
) //true
Copy the code
Every () runs the given function on each item in the array, and returns true if the function returns true for each item.
console.log([1, 2, 3, 4, 5].every(function (item, index, array) {
return item > 3
})
) //false
Copy the code
Filter () returns an array of items that return true by running the given function on each item in the array.
console.log([1, 2, 3, 4, 5].filter(function (item, index, array) {
return item > 3
})
) //[4, 5]
Copy the code
ForEach () runs the given function on each item in the array, returning no value.
Console. log([1, 2, 3]. ForEach (function (item, index, array) {console.log(item, index, array) // 1 0 [1, 2, 3]. 3] // 2 1 [1, 2, 3] // 3 2 [1, 2, 3] }) ) //undefinedCopy the code
Map () runs the given function on each item in the array, returning an array of the results of each function call.
console.log([1, 2, 3].map(function (item, index, array) {
return item * 2
})
) //[2, 4, 6]
Copy the code
Merge methods reduce() & reduceRight()
Both of these methods iterate over all the items in the array and then build a final value that is returned. Actually reduce() starts from the first item in the array and goes through it one by one to the end, while reduceRight() does the opposite. Both methods take two parameters, the function called on each item, and the initial value that serves as the basis for merging. The function called on each item takes four arguments, the previous value, the current value, the item’s index, and an array object, and any return value from this function is automatically passed to the next item as the first argument. In this function, the first iteration occurs on the second item of the array, so the first argument is the first item of the array, and the second argument is the second item of the array
console.log([1, 2, 3].reduce(function (prev, cur, index, array) {
return prev + cur
})
) //6
Copy the code
ES6
Extended operators…
You can expand an array and convert it to a sequence of parameters.
console.log(... [1, 2, 3]) //1 2 3Copy the code
Traversal mode for… of
for… The traversal mode of “of” can be customized, and the traversal mode can be “for”, “for”… In understand the realization
for (let item of [1, 2, 3]) {
console.log(item)
}
// 1
// 2
// 3
for (let item of [1, 2, 3].values()) {
console.log(item)
}
// 1
// 2
// 3
for (let item of [1, 2, 3].keys()) {
console.log(item)
}
// 0
// 1
// 2
for (let item of [1, 2, 3].entries()) {
console.log(item)
}
// [0, 1]
// [1, 2]
// [2, 3]
Copy the code
There is a point worth noting here, for… The in loop can also iterate over each item in the array, but with for… Each item in the array iterated by the in loop is converted to a string instead of the original data type.
from()
Array-like objects and traversable objects can be converted to real arrays, with the important note that the length property must be given, otherwise the array is empty.
var obj = {
0: 1,
1: 2,
2: 3,
length: 3
}
console.log(Array.from(obj)) // [1, 2, 3]
Copy the code
of()
Of () always returns an array of parameter values, or an empty array if there are no parameters.
console.log(Array.of(1, 2, 3, 4)) // [1, 2, 3, 4]
console.log(Array.of()) // []
Copy the code
copyWithin(target, start, end)
Inside the current array, copies the member at the specified location to another location, and returns the current array. If the value is negative, the value is reciprocal. If the value is negative, the value starts reading from the end. If the value is negative, the value starts reading from the end. If the value is negative, it is calculated from the end. It changes the original array.
console.log([1, 2, 3, 4, 5, 6].copyWithin(3, 0)) // [1, 2, 3, 1, 2, 3] console.log([1, 2, 3, 4, 5, 6].copyWithin(-6, //[4, 5, 6, 4, 5, 6]Copy the code
find() & findIndex()
Find () is used to find the first qualifying array, passing in a callback function that executes on all items in the array until the first qualifying item is found and returns, or undefined if none is found.
console.log([1, 2, 3, 4, 5].find(function (i) {
return i > 3
})
) //4
Copy the code
FindIndex () is similar to find() except that findIndex() returns the first eligible index or -1 if there is no eligible entry.
console.log([1, 2, 3, 4, 5].find(function (i) {
return i > 3
})
) //3
Copy the code
fill(value,start,end)
Fills an array with the given value and returns the filled array. Value Indicates the fill value. Start indicates the start position and end indicates the end position.
console.log([1, 2, 3, 4, 5].fill(6, 0, 6)) //[6, 6, 6, 6, 6]
Copy the code
keys() & values() & entries()
All three methods are used to iterate over groups of numbers and return a traverser object, the only differences being that keys() is traversal of key names, values() is traversal of key values, and entries() is traversal of key and value pairs. In the for… These three methods have already been used in OF, so I won’t repeat them here, just supplement them.
Entries () can be retrieved in one of two ways, as key-value pairs, or as arrays.
for (var [index, elem] of [1, 2, 3].entries()) {
console.log(index, elem)
}
//0 1
//1 2
//2 3
for (var i of [1, 2, 3].entries()) {
console.log(i)
}
//[0, 1]
//[1, 2]
//[2, 3]
Copy the code
ES7
includes()
Used to check if the array contains a given value, returning true if it does, false if it does not.
console.log([1, 2, 3].includes(2)) //true
console.log([1, 2, 3].includes('2')) //false
Copy the code
One notable point here is that includes() addresses the misjudgment of NaN by indexOf().
console.log([1, 2, NaN].indexOf(NaN)) //-1
console.log([1, 2, NaN].includes(NaN)) //true
Copy the code
ES10
flat() & flatMap()
Flat () can take subarrays of nested arrays and add them in their original places. By default, this array fetches only the first layer of the subarray. If you want to fetch multiple layers, you can add an argument to specify the number of layers to fetch. If there is a vacancy in the array, the flat() method skips the vacancy.
var arr = [1, 2, 3, [4, 5, 6, [7, 8, 9]]]
console.log(arr.flat()) //[1, 2, 3, 4, 5, 6, [7, 8, 9]]
console.log(arr.flat(2)) //[1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log([1, 2, , 4, 5].flat()) //[1, 2, 4, 5]
Copy the code
FlatMap () performs a callback on each member of the array and then executes the Flat () method on the array of returned values, which returns a new array without changing the original array. FlatMap () can expand only one array, and the callback can pass in three arguments: currentValue (the element being processed in the array), index (the index of the element being processed in the array), array (the map array being called), thisArg, and traversal to this
arr.flatMap(function callback(currentValue[, index[, array]]) {
// ...
}[, thisArg])
console.log([1, 2, 3].flatMap((x) => [x * 2])) //[2, 4, 6]
console.log([1, 2, 3].flatMap((x) => [[x * 2]])) //[[2], [4], [6]]
console.log([1, 2, 3, [4, 5, 6, [7, 8, 9]]].flatMap(function (i) {
return i * 2
})
) //[2, 4, 6, NaN]
Copy the code
At the end
This article has covered only the basics of using JavaScript array methods. If you want to learn more, check out the Little Red Book, The Rhino Book, or getting started with the ES6 standard. Please correct any deficiencies or mistakes.
Here are two tips for manipulating JavaScript arrays.
Unlock various JS array operations, there is always something you want!
JS array kit Kat trick
The resources
- JavaScript Advanced Programming (Version 4)
- Introduction to ES6 Standards (3rd Edition)