map()

  1. let arr = [56,61,88,97,42]
  2. let result = arr.map(function(item){
  3. return item <= 60 ? '不及格' : '及格'
  4. })
  5. console.log(result) //["不及格", "及格", "及格", "及格", "不及格"]
  6. //还可以使用箭头函数简写
  7. let result = arr.map(item => item <= 60 ? '不及格' : '及格')
  8. //是不是很高大上

reduce()

arr.reduce( function(tmp, item, index){
三个参数:
tmp 上一次计算的临时结果
item 数组的元素
index 数组的下标

} )

  1. let arr = [1,2,3,4,5,6,7,8,9,10]
  2. //比如给整个数组求和
  3. let result = arr.reduce((tmp, item, index) => {
  4. return tmp + item
  5. })
  6. console.log(result) // 55
  7. //比如给数组求平均值
  8. let result = arr.reduce((tmp, item, index) => {
  9. let length = arr.length
  10. if(index != length - 1){ //如果不是最后一个元素,求和
  11. return tmp + item
  12. }else{//如果是最后一个元素,先求和再求平均值
  13. return (tmp + item) / length
  14. }
  15. })
  16. console.log(result) // 5.5

filter()

filter( function(item){
//返回布尔值
} )

  1. let arr = [1,2,3,4,5,6,7,8,9,10]
  2. //找出能被3整除的数
  3. let result = arr.filter(item => item % 3 == 0)
  4. console.log(result) // [3, 6, 9]
  5. //再举一个例子
  6. let arr = [
  7. {name: '男士包', price: 65},
  8. {name: '女士包', price: 6500},
  9. {name: '男士鞋', price: 165},
  10. {name: '女士鞋', price: 1065},
  11. ]
  12. //价格大于1000的商品
  13. let results = arr.filter(item = >item.price >= 1000)
  14. console.log(results)
  15. /*
  16. 0: {name: "女士包", price: 6500}
  17. 1: {name: "女士鞋", price: 1065}
  18. */

forEach()

(value, index, array)三个参数

  1. let arr = [1,2,3,10,[3,3],{a:1,b:23}]
  2. arr.forEach( (value, index, array) => {
  3. console.log(value, index ,array)
  4. })
  5. /*
  6. 1 0 (6) [1, 2, 3, 10, Array(2), {…}]
  7. 2 1 (6) [1, 2, 3, 10, Array(2), {…}]
  8. 3 2 (6) [1, 2, 3, 10, Array(2), {…}]
  9. 10 3 (6) [1, 2, 3, 10, Array(2), {…}]
  10. (2) [3, 3] 4 (6) [1, 2, 3, 10, Array(2), {…}]
  11. {a: 1, b: 23} 5 (6) [1, 2, 3, 10, Array(2), {…}]
  12. */