preface
Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”. Can you do Array? Today, to share the small knowledge is JS native array attached to a variety of methods, can master these methods, your development efficiency will be significantly improved, the code is not only elegant and reliable, but also to avoid being dominated by a variety of bugs! Let’s cut to the chase.
▶ Overview of array methods
☛ traversal
array.forEach()
Master index: ★★★★★
Method description:
Used to call each element of the array and pass the element to the callback function
Grammar:
array.forEach(function(currentValue, index, arr), thisValue)
Copy the code
Example:
let names = ['Jojo'.'Machine'.'Mikes'.'John'.'James'.'Chris'];
names.forEach((item, index, arr) = > {
console.log(`names = [${arr}] `);
console.log(`names[${index}] = ${item}`);
})
Copy the code
Console:
Note:forEach()
Callbacks are not executed for empty arrays
array.map()
Master index: ★★★★★
Method description:
Returns a new array in which the elements are processed in the order of the original array elements
Grammar:
array.map(
function(CurrentValue (required; Current element), index(selected; Subscript of each element), arr(selected; Array of objects to which the element belongs.),
thisValue(Optional. Object is used when the callback is executed, passed to the function, and used as"this"The value of the))Copy the code
Example:
let arr1 = ['apple'.'banana'.'bear'.'watermelon'];
let arr2 = arr1.map((currentValue, index) = > {
if (index >= 2) {
return currentValue + 's';
}
return currentValue;
});
console.log(arr2);
Copy the code
Example description:
This example suffixes elements with subscript 2 and later in the array with ‘s’, returning a new array arR2
Console:
Note:
map()
Empty arrays are not checkedmap()
It doesn’t change the original array
array.every()
★★★
Method description:
Used to check whether all elements of an array meet the specified criteria (provided by a function), the every() method uses the specified function to check all elements in the array: if one element in the array does not meet the specified criteria, the entire expression returns false, and the remaining elements are not tested. Returns true if all elements satisfy the condition. In short, the logic of this method is like &&
Grammar:
array.every(function(currentValue, index, arr), thisValue)
Copy the code
Example:
let ages = [18.19.29.40.21];
let ifAdult = ages.every((currentValue, index, ages) = > {
return currentValue >= 18;
});
console.log(ifAdult ? 'Congratulations on being adults! ' : 'At least one of them is a minor! ');
Copy the code
Console:
Note:
every()
Empty arrays are not checkedevery()
It doesn’t change the original array
array.some()
★★★
Method description:
For the same reason, see ☝
Grammar:
array.some(function(currentValue, index, arr), thisValue)
Copy the code
Example:
ages.push(10);
let ifAdultFlag = ages.some((currentValue) = > {
return currentValue < 18; // Return true if at least one condition is met, false otherwise
});
console.log(! ifAdultFlag ?'Congratulations on being adults! ' : 'At least one of them is a minor! ');
Copy the code
Console:
Note:
some()
Empty arrays are not checkedsome()
It doesn’t change the original array
array.filter()
Master index: ★★★★
Method description:
Creates a new array of elements by checking all the elements in the specified array
Grammar:
array.filter(function(currentValue, index, arr), thisValue)
Copy the code
Example:
let arr3 = arr1.filter((currentValue) = > {
return currentValue.length > 4;
});
console.log(arr3);
Copy the code
Console:
Note:
filter()
Empty arrays are not checkedfilter()
It doesn’t change the original array
array.reduce()
Master index: ★★★★★
Method description:
Receiving a function as an accumulator, each value in the array (from left to right) is reduced to a value
Grammar:
array.reduce(function(Total (required; Return value after calculation), currentValue(required; Current element), currentIndex(optional), ARR (optional; The object to which the current element belongs)),
initialValue(The initial value of the accumulator))Copy the code
Example:
let arr4 = [13.2.23.4.23.1.13.2.13.0.20.26];
let result1 = arr4.reduce((total, currentValue) = > {
total += currentValue;
return total;
}, 0);
let result2 = arr1.reduce((total, currentValue, currentIndex) = > {
if(currentIndex ! = arr1.length -1) {
return total + currentValue + '|';
}
return total + currentValue;
}, 'begin to sum -> ')
console.log(result1);
console.log(result2);
Copy the code
Example description:
Here, each value in the ARR4 array is added to the total variable. The initial value of total is 0, and the final cumulative sum is put into result1. Also similarly to a string array, each element in the array arr1 spliced into ‘the begin to sum – > string behind, and using the’ | ‘as the separator between elements and elements, until the last element behind without separator
Console:
Note: Reduce () does not perform a callback for an empty array
☛ stitching
array.concat()
Master index: ★★★★
Method description:
Takes multiple arrays as arguments and returns the concatenated array
Grammar:
array.concat(array2, array3, ... , arrayX(can concatenate multiple arrays)Copy the code
Example:
let array1 = [1.2.3.4.5];
let array2 = [6.7.8.9.10];
let array3 = [11.12.13.14.15];
let newArr1 = array1.concat(array2, array3);
let newArr2 = array1 + array2 + array3;
console.log(`newArr1 = [${newArr1}], its data type:The ${typeof (newArr1)}`);
console.log(`newArr2 = ${newArr2}, its data type:The ${typeof (newArr2)}`);
Copy the code
Example description:
The + method is different from the concat(array) method. The + method is a string method and the concat(array) method, so the returned data type is array (object) and string. NewArr2 is the result of string concatenation after array.toString()
Console:
array.join()
Master index: ★★★★
Method description:
Concatenate each element of the array with the specified delimiter, resulting in a string
Grammar:
array.join(separator)
Copy the code
Example:
let arrToString1 = site.join('|');
let arrToString2 = names.join(' and ');
let arrToString3 = ages.join();
console.log(arrToString1);
console.log(arrToString2);
console.log(arrToString3);
Copy the code
Console:
Note: You need to specify the delimiter to use. If this parameter is omitted, a comma is used as a delimiter
Aid Element Lookup
array.find()
Master index: ★★★★★
Method description:
Finds the value of the first element in the array that passed the test, returns the value if found, undefined otherwise
Grammar:
array.find(function(currentValue, index, arr), thisValue)
Copy the code
Example:
let names = ['Jojo'.'Machine'.'Mikes'.'John'.'James'.'Chris'];
let name = names.find((currentValue, index) = > {
return currentValue.length > 5 && index < 5; // Returns the first value that matches the condition
});
console.log(name);
Copy the code
Example description:
The find() method calls the function execution once for each element in the array. When the element in the array returns true when testing the condition, find() returns the element that matches the condition, and the subsequent value does not call the execution function. Returns undefined if there are no eligible elements
Console:
Note:
find()
For an empty array, the function is not executedfind()
It doesn’t change the original value of the array
array.findIndex()
★★★
Method description:
Returns the position of the first element of the array passed in to test the condition
Grammar:
array.find(function(currentValue, index, arr), thisValue)
Copy the code
Example:
let nameIndex = names.findIndex((currentValue, index) = > {
return currentValue.length > 4 && index > 1; // Returns the index of the first qualifying element
});
console.log(nameIndex);
Copy the code
Console:
array.indexOf()
★★★
Method description:
Returns the position of a specified element in the array, or -1 if the specified element is not found
Grammar:
Array.indexof (item(the element to be searched), start(the index position to start the search, if this parameter is missing start the search)Copy the code
Example:
let site = ['baidu'.'taobao'.'tencent'.'alibaba'];
let eleIndex = site.indexOf('taobao');
console.log(The taobao element index of the 'site array is:${eleIndex}`);
let eleIndex2 = site.indexOf('taobao'.2);
console.log(`${eleIndex2 == -1 ? Mysql > select element taobao from array index 2 : 'taobao' is found at index 2.}`);
Copy the code
Console:
array.includes()
Master index: ★★★★
Method description:
Returns true if an array contains a specified element, false otherwise
Grammar:
Array.includes (item)Copy the code
Example:
let site = ['baidu'.'taobao'.'tencent'.'alibaba'];
console.log(Is the 'site' array containing Tencent:${site.includes('tencent')?'tick' : The '*'}`);
console.log(Whether the 'site' array contains Google:${site.includes('google')?'tick' : The '*'}`);
Copy the code
Console:
Aid the aid of the aid element
array.push()
Master index: ★★★★★
Method description:
You can add one or more elements to the end of an array and return a new length
Grammar:
array.push(item1, item2, ... , itemX)Copy the code
Example:
let newLen = names.push('harden'.'mercy'.'marry');
console.log(`names = [${names}], adding multiple elements to the end of the array succeeded! The current length of the array is:${newLen}`);
Copy the code
Console:
array.pop()
Master index: ★★★★★
Method description:
Removes the last element of an array and returns the deleted element
Grammar:
array.pop()
Copy the code
Example:
console.log(`names = [${names}] `);
let lastElement = names.pop();
console.log('has removed the last element in the Names array, which is:${lastElement}`);
console.log(`names = [${names}] `);
Copy the code
Console:
Note:
- This method changes the length of the array
- To remove the first element of the array, use the
shift()
methods
array.shift()
★★★
Method description:
Removes the first element from an array and returns the value of the first element
Grammar:
array.shift()
Copy the code
Example:
let firstElement = names.shift();
console.log('has removed the first element in the Names array, which is:${firstElement}`);
console.log(`names = [${names}] `);
Copy the code
Console:
Note:
- This method changes the length of the array
- To remove the last element of the array, use the
pop()
methods
array.unshift()
★★★
Method description:
You can add one or more elements to the beginning of an array and return a new length
Grammar:
array.unshift(item1, item2, ... , itemX)Copy the code
Example:
let newLength = names.unshift('jordan'.'robot'.'rose'.'karry');
console.log(`names = [${names}], adding multiple elements to the beginning of the array succeeded! The current length of the array is:${newLength}`);
Copy the code
Console:
array.slice()
Master index: ★★★★★
Method description:
Returns selected elements from an existing array. Returns a new array containing elements from the arrayObject from start to end (excluding the element)
Grammar:
Array. slice(start), end(end))Copy the code
Illustration:
Example:
let nums = [1.2.3.4.5];
let newNums = nums.slice(-3, -1);
console.log(newNums); // Returns a new array, but does not affect the original array
console.log('Cut the last four elements:${nums.slice(-4)}`);
Copy the code
Example description:
Slice (-3, -1) reads elements from the array using negative numbers (from the third to last element of the array (included) to the last to last (not included))
Console:
Note:
start
Specify where to start, can be negativeend
Specify where to end the selection, or it can be negativeslice()
Method does not alter the original array
array.sort()
Master index: ★★★★★
Method description:
Used to sort the elements of an array
Grammar:
Array.sort (sortFunction (sortfunction))Copy the code
Example:
let points1 = [40.100.1.5.25.10];
let points2 = ['e'.'b'.'t'.'z'.'d'.'k'];
// Sort in ascending order from smallest to largest
points1.sort(function (a, b) { return a - b; });
// The default sort order is alphabetical ascending
points2.sort();
console.log('array sorted from smallest to largest:${points1.join('<')}`);
console.log('Default sort order is alphabetical ascending:${points2.join('<')}`);
// Sort in descending order from highest to lowest value
points1.sort((a, b) = > {
return b - a;
})
console.log('array sorted from largest to smallest:${points1.join('>')}`);
// If you want to change the default alphabetic sort to descending order, use the reverse() method
console.log('Change the default sort order to alphabetically descending:${names.sort().reverse().join('>')}`);
Copy the code
Console:
Note:
- When numbers are in alphabetical order “30” will come before “4”
- To use numeric sort, you must call it with a function as an argument
- The function specifies whether numbers are sorted in ascending or descending order
- Using this method changes the original array
- The default sort order is alphabetical ascending
- If you want to change the default alphabetic sort to descending order, you need to
array.reverse()
methods
☛ iterator
Symbol.iterator
Master index: ★★★★
Description:
Iterator is a new iteration mechanism introduced in ES6. It is a unified interface that can be used to iterate over String, Array, Map, Set and other data structures. It is realized through a method whose key is symbol. Iterator
Example:
let users = [
{ name: 'Joe'.password: 'zhangsan123' },
{ name: 'bill'.password: 'lisi123' },
{ name: 'Cathy'.password: 'wangwu123' },
{ name: 'liu six'.password: 'liuliu123' }];
let it = users[Symbol.iterator]();
while (true) {
let cur = it.next();
if (cur.done) { // Whether the pointer position reaches the end
break;
} else {
console.log(cur); }}Copy the code
Example description:
Build an iterator to the array using Users [symbol.iterator]() that points to the start of the current data structure. The next method iterates down to the next location, which returns the object at the current location. Value and Done are the two properties of the current object, and the loop ends when done is true
Console:
array.keys()
★★★
Method description:
Used to create an iterable containing an array key from an array
Grammar:
array.keys()
Copy the code
Example:
let users = [
{ name: 'Joe'.password: 'zhangsan123' },
{ name: 'bill'.password: 'lisi123' },
{ name: 'Cathy'.password: 'wangwu123' },
{ name: 'liu six'.password: 'liuliu123' }];
console.log(users.keys()); // Array Iterater
let it = users.keys();
for (let key of users.keys()) {
console.log(it.next().value);
console.log(The first `${key + 1}Bit user name:${users[key].name}`);
}
Copy the code
Console:
array.values()
Master index: ★★★★
Method description:
Returns a new Array Iterator containing the value of each subscript in the Array
Grammar:
array.values()
Copy the code
Example:
let users = [
{ name: 'Joe'.password: 'zhangsan123' },
{ name: 'bill'.password: 'lisi123' },
{ name: 'Cathy'.password: 'wangwu123' },
{ name: 'liu six'.password: 'liuliu123' }];
let iterator = names.values();
for (let it of iterator) {
console.log(it);
}
Copy the code
Console:
array.entries()
Master index: ★★★★
Method description:
Returns an iterator of an array containing the array’s key/value pairs.
Grammar:
array.entries()
Copy the code
Example:
let programs = ["Java"."JavaScript"."C++"."Python"];
let entries = programs.entries();
// console.log(entries.next().value);
// console.log(entries.next().value);
// console.log(entries.next().value);
// console.log(entries.next().value);
for (const [key, value] of entries) {
console.log(`key: ${key} => value: ${value}`);
}
Copy the code
Example description:
The index value of the array in the iterated object is the key, and the array element is the value. If the code comment section is not commented out, then the next pointer has reached the end of entries, for… Of entries to nothing
Console:
Dynamic method
Array.from()
Master index: ★★★★★
Method description:
Used to return an array from an object that has a length attribute or an iterable object
Grammar:
Array. From (object, mapFunction, thisValue(mapFunction)thisObject). )Copy the code
Example:
let setObj = new Set(['a'.'b'.'c'.'a'.'b'.'c']);
console.log(setObj);
let arrObj = Array.from(setObj, (item, index) = > {
return item + index;
}); // An array is returned
console.log(arrObj);
let arrr = Array.from(arrObj.entries());
console.log(arrr);
Copy the code
Example description:
First, initialize a Set, then concatenate each element with its subscripts, using Array’s static from method to combine the concatenated elements into a new Array. Similarly, you can assemble an array that returns a new arrobj.entries () iterable
Console:
Array.isArray()
Method description:
Master index: ★★★★
Used to determine whether an object is an array. Return true if the object is an array, false otherwise
Example:
let site = ['baidu'.'taobao'.'tencent'.'alibaba'];
let ifArray = Array.isArray(site);
console.log(`${ifArray ? 'site is an array! ' : 'site is not an array! '}`);
Copy the code
Console:
Note: it isArray.isarray (Array name)
Rather thanThe array name. IsArray ()
☛ other
array.reverse()
★★★
Method description:
Used to reverse the order of elements in an array
Grammar:
array.reverse()
Copy the code
Example:
console.log('originally, site = [${site}] `);
site.reverse();
console.log('site = [${site}] `);
Copy the code
Console:
Note: changes the original array
array.toString()
Master index: ★★
Method description:
Converts an array to a string and returns the result
Grammar:
array.toString()
Copy the code
Example:
console.log('converts an array to a string, separated by commas:${points2.toString()}`)
Copy the code
Console:
array.valueOf()
Master index: ★★
Method description:
Mandatory Array Original value of an object
Grammar:
array.valueOf()
Copy the code
Example:
console.log(site.valueOf());
/ / with the following
console.log(site);
Copy the code
Example description:
The original value is inherited by all objects derived from the Array object. The valueOf() method is usually called automatically in the background by JavaScript and does not appear explicitly in the code
Console:
Note:valueOf()
Method does not change the original array
At the end
Writing is not easy, welcome everyone to like, comment, your attention, like is my unremitting power, thank you to see here! Peace and Love.