1.map
映射,即原数组映射成一个新的数组,map方法接受一个新参数,这个参数就是将原数组变成新数组的映射关系。
//用map取出指定元素
let arr = [
{name:'小明',age:16,sex:'男'},
{name:'小红',age:17,sex:'女'},
{name:'小李',age:18,sex:'女'},
]
let result = arr.map(item => {
return item.name + '--'+item.sex
})
console.log(result)
2.reduce
reduce() 方法接受四个参数:初始在这里插入代码片
值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce() 的数组。
//用reduce计算数组的和
let arr = [10,20,30,40]
let result = arr.reduce(function(tmp,item,index){
return tmp+item
})
console.log(result) //100
1.tmp,item,index 分别是什么?
let arr = [10,20,30,40]
let result = arr.reduce(function(tmp,item,index){
console.log(tmp,item,index)
})
可以看到 arr[10,20,30,40]
第一次 tmp = 10,item=20,index=1
第二次 tmp = undefined,item=30,index=2
第三次 tmp = undefined,item=40,index=3
所以index =下标 item = 值 tmp默认等于arr[0]
2.计算过程
3.filter
filter方法过滤掉不符合条件的值,返回一个符合条件的新的数组
//去除age大于16的学生信息
let arr = [
{name:'小明',age:16,sex:'男'},
{name:'小红',age:17,sex:'女'},
{name:'小李',age:18,sex:'女'},
]
let result = arr.filter(item => item.age > 16)
console.log(result)
4.forEach
循环
let arr = [
{name:'小明',age:16,sex:'男'},
{name:'小红',age:17,sex:'女'},
{name:'小李',age:18,sex:'女'},
]
let result = arr.forEach(item => {
console.log(item)
})
5.find
找到数组中第一个符合条件的数据
let arr = [
{name:'zhangsan',age:10},
{name:'lisi',age:5},
{name:'xiaomage',age:8}
]
let result = arr.find((arr)=>{
return arr.age == 5
})
console.log(result)
6.some
只要有一个条件符合,就为true
let arr = [
{name:'zhangsan',age:10},
{name:'lisi',age:5},
{name:'xiaomage',age:8}
]
let result = arr.some((arr)=>{
return arr.age > 9
})
console.log('结果为:'+result)
7.every
与some相反,只要一个不符合,就为false
let arr = [
{name:'zhangsan',age:10},
{name:'lisi',age:5},
{name:'xiaomage',age:8}
]
let result = arr.every((arr)=>{
return arr.age > 7
})
console.log('结果为:'+result)
}