es5 数组新增加的方法
1.forEach
let arr = ['aaa', 'bbb', 'ccc'] arr.forEach((item, index, array) => { console.log(val, index, arr) })
类似于,for循环
2.map
正常情况下,需要配合return来返回一个新的数组,如果没有return, 则相当于forEach
let arr = [ {name: '小明', sex: '男', age: 15}, {name: '小红', sex: '女', age: 13}, {name: '小东', sex: '男', age: 17}, {name: '小强', sex: '男', age: 14} ] let newArr = arr.map((item, index, array) => { if (item.age > 16) { return item.name + '已成年' } else { return item.name + '未成年' } }) console.log(newArr)
3.filter
过滤, 返回一个新的数组
let arr = [ {name: '小明', sex: '男', age: 15}, {name: '小红', sex: '女', age: 13}, {name: '小东', sex: '男', age: 17}, {name: '小强', sex: '男', age: 14} ] let newArr = arr.filter((item, index, array) => {return item.age < 16 }) console.log(newArr)
4.some
按照我的理解就是判断数组中是否有满足条件的项
let arr = [ {name: '小明', sex: '男', age: 15}, {name: '小红', sex: '女', age: 13}, {name: '小东', sex: '男', age: 17}, {name: '小强', sex: '男', age: 14} ] let newArr = arr.some((item, index, array) => { return item.age < 16 }) console.log(newArr)
5.every
判断数组中是否每一项都满足条件
let arr = [ {name: '小明', sex: '男', age: 15}, {name: '小红', sex: '女', age: 13}, {name: '小东', sex: '男', age: 17}, {name: '小强', sex: '男', age: 14} ] let newArr = arr.every((item, index, array) => { return item.age < 16 }) console.log(newArr)
6.reduce
类似于递归函数,从左往右循环
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let res = arr.reduce((prev, cur, index, array) => { return prev + cur }) console.log(res)
7、reducerRight
类似于递归函数,从右往左循环