当前位置:网站首页>Array common operation methods sorting (including ES6) and detailed use
Array common operation methods sorting (including ES6) and detailed use
2022-07-03 00:29:00 【Zixuan Pavilion】
Catalog
1. every()
2. some()
3. filter()
4. map()
5. reduce()
6. forEach() Traverse
7. find() lookup
8. for loop
9. for in
10. for of
11. findIndex()
12. includes()
13. concat Merge
14. Extension operator …
15. indexOf() and lastIndexOf()
Array common operation methods sorting ( contain es6) And detailed use .
1. every()
Judge whether all elements of the array meet the conditions return Boolean Boolean value :true/false
Only when all meet true
let arr = [1,6,9,10,100,25];
const e = arr.every(item => item > 2);// Determine whether they are greater than 2
console.log(e);// false
2. some()
Judge whether all elements of the array meet the conditions return Boolean Boolean value :true/false
As long as one of the conditions is met, it is true
let arr = [1,6,9,10,100,25];
const s = arr.some(item => item > 2);// Determine whether there is more than 2 Of
console.log(s);// true
3. filter()
Filter array Create and return a new array that meets the conditions ( Do not change the original array )
Be careful :filter Function is just a filtering function , You can't change the elements 、 Operational elements
let arr = [1,6,9,10,100,25]
const f=arr.filter(item=>item%2===0);// Returns an even number
console.log(f); // [6, 10, 100]
console.log(arr); // [1,6,9,10,100,25]
4. map()
You can change the array one by one Create a new array and return ( Do not change the original array )
grammar :let newArray = oldArray.map((item, index, arr) => {}) item The current element 、index Current index 、arr Original array
let arr = [1,6,9,10,100,25];
const newArr=arr.map(item=>{
if(item %2===0) item=item*10 ;return item });// even numbers *10
console.log(newArr);// [1, 60, 9, 100, 1000, 25] Returns an array of the results of each operation
console.log(arr);// [1,6,9,10,100,25]
// Be careful
const newArr2=arr.map(item=>item%2===0) // Returns an array of Boolean values
console.log(newArr2);// [false, true, false, true, true, false]
5. reduce()
Call the specified callback function for each element in the array ( Custom accumulator ), The return value of the callback function is the cumulative result , And this return value is provided as a parameter the next time the callback function is called
grammar :let newArray =arr.reduce((prev Cumulative return value of completed calculation ,cur The current element ,index Index of the current element ,arr The array object to which the current element belongs )=>{}, Initial value )
Most abbreviated :arr.reduce((pre,cur)=>{
}, Initial value )
Primary applications
// Common summation 、 Find the product
let arr = [1,6,9,10,100,25];
const r = arr.reduce((pre,item)=>pre+=item,0);// Calculating the sum of arrays
console.log(r);// 151
// Object property summation
let arr2 = [{
name:' Chinese language and literature ',score:120},{
name:' mathematics ',score:130},{
name:' English ',score:113}];
const r2 = arr2.reduce((pre,item)=>pre+=item.score,0);
console.log(r2); //363
Advanced applications
// Count the number of occurrences of each element in the array
let arr= ['a','b','c','d','b','a','c','a','e'];
let r=arr.reduce((obj,item)=>{
obj[item]=obj[item]?obj[item]+1:1;return obj},{
});
console.log(r);// {a: 3, b: 2, c: 2, d: 1, e: 1}
// duplicate removal
let arr= ['a','b','c','d','b','a','c','a','e'];
let r=arr.reduce((newArr,item)=>{
!newArr.includes(item)&&newArr.push(item);return newArr},[]);
console.log(r);// ["a", "b", "c", "d", "e"]
// Two dimensional array to one dimension
let arr = [[0, 1], [2, 3], [4, 5]]
let r=arr.reduce((pre,item)=>[...pre,...item],[])
console.log(r);// [0, 1, 2, 3, 4, 5]
// Multidimensional to one-dimensional
let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const fn=(arr)=>{
return arr.reduce((pre,item)=>pre.concat(Array.isArray(item)?fn(item):item),[])
}
console.log(fn(arr));// [0, 1, 2, 3, 4, 5, 6, 7]
6. forEach() Traverse
Traversal array , Will change the original array , Execution result will not be returned
grammar :Array.forEach((item,index,arr)=>{}); item The current element 、index Current index 、arr Original array
let arr = [1,6,9,10,100,25];
const r=arr.forEach((item,index)=>arr[index]=item*2);
console.log(r);// undefined
console.log(arr);// [2, 12, 18, 20, 200, 50]
7. find() lookup
Returns the first qualified value Parameter is callback function ( Find and return to object No further traversal )
grammar :Array.find((value,index,arr) => {
return value > 2}) ;value Current value ,index Current index ,arr Original array
let arr = [1,6,9,10,100,25];
let r= arr.find((value,index,arr) => {
return value > 2})// Find the first one greater than 2 Of
console.log(r);// 6
let arr2 = [{
name:' Chinese language and literature ',score:120},{
name:' mathematics ',score:130},{
name:' English ',score:113}];
let r2=arr2.find(item=>item.name==' Chinese language and literature ')
console.log(r2);// {name:' Chinese language and literature ',score:120}
8. for loop
let arr = [1,6,9,10,100,25];
// Loop printing
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]); // Output... In sequence 1 6 9 10 100 25
}
// multiplication table
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= i; j++) {
document.write(i + "*" + j + "=" + (i * j) + " ");
if (j == i) {
document.write("<br/>");
}
}
}
9. for in
let arr = [1,6,9,10,100,25];
for (let i in arr) {
console.log(arr[i]); // Output... In sequence 1 6 9 10 100 25
}
10. for of
let arr = [1,6,9,10,100,25];
for (let i of arr) {
console.log(i); // Output... In sequence 1 6 9 10 100 25
}
11. findIndex()
Returns the first qualified index , Parameter is callback function
grammar :Array.findIndex((value,index,arr) => {
return value > 2}) ;value Current value ,index Current index ,arr Original array
let arr = [1,6,9,10,100,25];
const r= arr.findIndex((value,index,arr) => {
return value > 2}) // 2
console.log(r);//1
let arr2 = [{
name:' Chinese language and literature ',score:120},{
name:' mathematics ',score:130},{
name:' English ',score:113}];
let index = arr2.findIndex(item => item.name === " mathematics ");
console.log(index);// Returns the first qualified index value 1 No return found -1
12. includes()
Check whether the array contains an element , return Boolean type
const t=[' Journey to the west ',' A dream of red mansions ',' The romance of The Three Kingdoms ',' Water margin ']
console.log(t.includes(' Journey to the west ')); // true
console.log(t.includes(' Tang's monk '));// false
13. concat Merge
let arr1=[1,2,3,4];
let arr2=[5,6,7,8];
let arr3=arr1.concat(arr2);
console.log(arr1);// [1,2,3,4]
console.log(arr2);// [5,6,7,8]
console.log(arr3);// [1,2,3,4,5,6,7,8]
14. Extension operator …
Can convert an array into Comma separated parameter sequence
const tfbodys=[' Jackson Yi ',' hanah ',' Juen-Kai Wang ']
function fn(){
console.log(arguments)}
fn(...tfbodys) // amount to fn(' Jackson Yi ',' hanah ',' Juen-Kai Wang ')
Merging of arrays
let arr1=[' Xiao Ming ',' Xiaohong ']
let arr2=[' the other woman ',' Little four ']
let arr3=[...arr1,...arr2]
console.log(arr3);// [' Xiao Ming ',' Xiaohong ',' the other woman ',' Little four ']
Array Clone
const x=['e','f','h']
const y=[...x]
console.log(y);// ['e','f','h']
Convert a pseudo array to a real array
let lis=document.querySelectorAll('li');// Pseudo array
// lis.push(' test ')// Report errors
let liArr=[...lis] // Become a true array
liArr.push(' test ')
console.log(liArr);// [li, li, li, li, li, " test "]
15. indexOf() and lastIndexOf()
indexOf(‘ character ’, You can specify where to start searching ) Find the first index number of a given element The default from the 0 Start looking for , There is no return -1
lastIndexOf() Find the last index of a given element Start looking for , There is no return -1
let arr= ['a','b','c','d','b','a','c','a','e'];
console.log(arr.indexOf('a')); // 0
console.log(arr.indexOf('a',1)); // 5
console.log(arr.lastIndexOf('a')); // 7
边栏推荐
- 教育学大佬是怎么找外文参考文献的?
- 简单聊聊运维监控的其他用途
- Program analysis and Optimization - 9 appendix XLA buffer assignment
- [shutter] Introduction to the official example of shutter Gallery (learning example | email application | retail application | wealth management application | travel application | news application | a
- Angled detection frame | calibrated depth feature for target detection (with implementation source code)
- v8
- Andorid gets the system title bar height
- node_ Modules cannot be deleted
- AcWing_188. 武士风度的牛_bfs
- Is there a specific format for English papers?
猜你喜欢
随机推荐
Should you study kubernetes?
Nc50528 sliding window
Sysdig analysis container system call
Form form instantiation
Slf4j + Logback日志框架
NC50965 Largest Rectangle in a Histogram
Install docker and use docker to install MySQL
[MCU project training] eight way answering machine
洛谷_P2010 [NOIP2016 普及组] 回文日期_折半枚举
How to specify const array in the global scope of rust- How to specify const array in global scope in Rust?
详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
英文论文有具体的格式吗?
Monitor container runtime tool Falco
[Chongqing Guangdong education] audio visual language reference materials of Xinyang Normal University
Gan model architecture in mm
多进程编程(一):基本概念
使用jenkins之二Job
AcWing_ 188. Warrior cattle_ bfs
Go自定义排序
微信小程序获取某个元素的信息(高、宽等),并将px转换为rpx。









