当前位置:网站首页>数组常用操作方法整理(包含es6)及详细使用
数组常用操作方法整理(包含es6)及详细使用
2022-07-02 23:06:00 【紫轩阁】
目录
1. every()
2. some()
3. filter()
4. map()
5. reduce()
6. forEach() 遍历
7. find() 查找
8. for循环
9. for in
10. for of
11. findIndex()
12. includes()
13. concat合并
14. 扩展运算符…
15. indexOf()和lastIndexOf()
数组常用操作方法整理(包含es6)及详细使用。
1. every()
判断数组所有元素是否全部符合条件 返回 Boolean 布尔值:true/false
全部符合才为true
let arr = [1,6,9,10,100,25];
const e = arr.every(item => item > 2);// 判断是否都大于2
console.log(e);// false
2. some()
判断数组所有元素是否有符合条件的 返回 Boolean 布尔值:true/false
只要有一项符合条件就为true
let arr = [1,6,9,10,100,25];
const s = arr.some(item => item > 2);// 判断是否有大于2的
console.log(s);// true
3. filter()
过滤数组 创建并返回一个符合条件的新数组(不改变原数组)
注意:filter函数只是筛选功能,不能改变元素、操作元素
let arr = [1,6,9,10,100,25]
const f=arr.filter(item=>item%2===0);// 返回偶数
console.log(f); // [6, 10, 100]
console.log(arr); // [1,6,9,10,100,25]
4. map()
可以逐个改变数组 创建并返回一个新数组(不改变原数组)
语法:let newArray = oldArray.map((item, index, arr) => {}) item当前元素、index当前索引、arr原数组
let arr = [1,6,9,10,100,25];
const newArr=arr.map(item=>{
if(item %2===0) item=item*10 ;return item });// 偶数*10
console.log(newArr);// [1, 60, 9, 100, 1000, 25] 返回的是每一项运算后的结果的数组
console.log(arr);// [1,6,9,10,100,25]
// 注意
const newArr2=arr.map(item=>item%2===0) // 返回的是布尔值组成的数组
console.log(newArr2);// [false, true, false, true, true, false]
5. reduce()
对数组中的每个元素调用指定的回调函数(自定义累计器),该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供
语法:let newArray =arr.reduce((prev累计完成计算的返回值,cur当前元素,index当前元素的索引,arr当前元素所属的数组对象)=>{},初始值)
最简写:arr.reduce((pre,cur)=>{
},初始值)
初级应用
// 常用求和、求乘积
let arr = [1,6,9,10,100,25];
const r = arr.reduce((pre,item)=>pre+=item,0);// 计算数组总和
console.log(r);// 151
// 对象属性求和
let arr2 = [{
name:'语文',score:120},{
name:'数学',score:130},{
name:'英语',score:113}];
const r2 = arr2.reduce((pre,item)=>pre+=item.score,0);
console.log(r2); //363
高级应用
// 计算数组中每个元素出现的次数
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}
// 去重
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"]
// 二维数组转一维
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]
// 多维转一维
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() 遍历
遍历数组,会修改原来的数组,不会返回执行结果
语法:Array.forEach((item,index,arr)=>{}); item当前元素、index当前索引、arr原数组
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() 查找
返回第一个符合条件的值 参数为回调函数 (找到立即返回object 不会再往下遍历)
语法:Array.find((value,index,arr) => {
return value > 2}) ;value当前值,index当前索引,arr原数组
let arr = [1,6,9,10,100,25];
let r= arr.find((value,index,arr) => {
return value > 2})// 找出第一个大于2的
console.log(r);// 6
let arr2 = [{
name:'语文',score:120},{
name:'数学',score:130},{
name:'英语',score:113}];
let r2=arr2.find(item=>item.name=='语文')
console.log(r2);// {name:'语文',score:120}
8. for循环
let arr = [1,6,9,10,100,25];
// 循环打印
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]); // 按顺序输出 1 6 9 10 100 25
}
// 九九乘法表
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]); // 按顺序输出 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); // 按顺序输出 1 6 9 10 100 25
}
11. findIndex()
返回第一个符合条件的索引,参数为回调函数
语法:Array.findIndex((value,index,arr) => {
return value > 2}) ;value当前值,index当前索引,arr原数组
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:'语文',score:120},{
name:'数学',score:130},{
name:'英语',score:113}];
let index = arr2.findIndex(item => item.name === "数学");
console.log(index);// 返回第一个符合条件的索引值1 找不到返回-1
12. includes()
检测数组是否包含某元素,返回Boolean类型
const t=['西游记','红楼梦','三国演义','水浒传']
console.log(t.includes('西游记')); // true
console.log(t.includes('唐僧'));// false
13. concat合并
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. 扩展运算符…
能将数组转换为 逗号分隔的参数序列
const tfbodys=['易烊千玺','王源','王俊凯']
function fn(){
console.log(arguments)}
fn(...tfbodys) // 相当于fn('易烊千玺','王源','王俊凯')
数组的合并
let arr1=['小明','小红']
let arr2=['小三','小四']
let arr3=[...arr1,...arr2]
console.log(arr3);// ['小明','小红','小三','小四']
数组克隆
const x=['e','f','h']
const y=[...x]
console.log(y);// ['e','f','h']
将伪数组转为真正的数组
let lis=document.querySelectorAll('li');// 伪数组
// lis.push('测试')// 报错
let liArr=[...lis] // 变成真数组
liArr.push('测试')
console.log(liArr);// [li, li, li, li, li, "测试"]
15. indexOf()和lastIndexOf()
indexOf(‘字符’,可指定开始查找的位置) 查找给定元素的第一个索引号 默认从0开始找,不存在返回-1
lastIndexOf() 查找给定元素的最后一个索引 从后开始找,不存在返回-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
边栏推荐
- 95 pages of smart education solutions 2022
- Happy Lantern Festival, how many of these technical lantern riddles can you guess correctly?
- MySQL advanced learning notes (4)
- zhvoice
- Using tensorflow to realize voiceprint recognition
- MySQL advanced learning notes (III)
- 有哪些比较推荐的论文翻译软件?
- LeedCode1480.一维数组的动态和
- 67 page overall planning and construction plan for a new smart city (download attached)
- How much do you know about synchronized?
猜你喜欢

Explain in detail the process of realizing Chinese text classification by CNN
![[shutter] Introduction to the official example of shutter Gallery (project introduction | engineering construction)](/img/f7/a8eb8e40b9ea25021751d7150936ac.jpg)
[shutter] Introduction to the official example of shutter Gallery (project introduction | engineering construction)

pageoffice-之bug修改之旅

详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图

How much do you know about synchronized?

Chinatelecom has maintained a strong momentum in the mobile phone user market, but China Mobile has opened a new track

sysdig分析容器系统调用

The privatization deployment of SaaS services is the most efficient | cloud efficiency engineer points north

论文的英文文献在哪找(除了知网)?

Additional: token; (don't read until you finish writing...)
随机推荐
How much do you know about synchronized?
Angled detection frame | calibrated depth feature for target detection (with implementation source code)
In February 2022, the ranking list of domestic databases: oceanbase regained its popularity with "three consecutive increases", and gaussdb is expected to achieve the largest increase this month
S12. Verify multi host SSH mutual access script based on key
Architecture: load balancing
有哪些比较推荐的论文翻译软件?
Chapter 3 of getting started with MySQL: database creation and operation
CMake基本使用
Interface automation coverage statistics - used by Jacobo
Custom throttling function six steps to deal with complex requirements
Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
maya渔屋建模
95页智慧教育解决方案2022
Slf4j + Logback日志框架
SQL query statement parameters are written successfully
[shutter] shutter photo wall (center component | wrap component | clickrrect component | stack component | positioned component | button combination component)
Interface difference test - diffy tool
Basic 10 of C language: array and pointer
MFC文件操作
FRP reverse proxy +msf get shell