map()
let arr = [56,61,88,97,42]
let result = arr.map(function(item){
return item <= 60 ? '不及格' : '及格'
})
console.log(result) //["不及格", "及格", "及格", "及格", "不及格"]
//还可以使用箭头函数简写
let result = arr.map(item => item <= 60 ? '不及格' : '及格')
//是不是很高大上
reduce()
arr.reduce( function(tmp, item, index){
三个参数:
tmp 上一次计算的临时结果
item 数组的元素
index 数组的下标
} )
let arr = [1,2,3,4,5,6,7,8,9,10]
//比如给整个数组求和
let result = arr.reduce((tmp, item, index) => {
return tmp + item
})
console.log(result) // 55
//比如给数组求平均值
let result = arr.reduce((tmp, item, index) => {
let length = arr.length
if(index != length - 1){ //如果不是最后一个元素,求和
return tmp + item
}else{//如果是最后一个元素,先求和再求平均值
return (tmp + item) / length
}
})
console.log(result) // 5.5
filter()
filter( function(item){
//返回布尔值
} )
let arr = [1,2,3,4,5,6,7,8,9,10]
//找出能被3整除的数
let result = arr.filter(item => item % 3 == 0)
console.log(result) // [3, 6, 9]
//再举一个例子
let arr = [
{name: '男士包', price: 65},
{name: '女士包', price: 6500},
{name: '男士鞋', price: 165},
{name: '女士鞋', price: 1065},
]
//价格大于1000的商品
let results = arr.filter(item = >item.price >= 1000)
console.log(results)
/*
0: {name: "女士包", price: 6500}
1: {name: "女士鞋", price: 1065}
*/
forEach()
(value, index, array)三个参数
let arr = [1,2,3,10,[3,3],{a:1,b:23}]
arr.forEach( (value, index, array) => {
console.log(value, index ,array)
})
/*
1 0 (6) [1, 2, 3, 10, Array(2), {…}]
2 1 (6) [1, 2, 3, 10, Array(2), {…}]
3 2 (6) [1, 2, 3, 10, Array(2), {…}]
10 3 (6) [1, 2, 3, 10, Array(2), {…}]
(2) [3, 3] 4 (6) [1, 2, 3, 10, Array(2), {…}]
{a: 1, b: 23} 5 (6) [1, 2, 3, 10, Array(2), {…}]
*/