var arr = [ {name:"张三",age:14}, {name:"李四",age:19}, {name:"王五",age:20}, ] let _arr = arr.filter(function(_a){ //这个参数代表数组中的参数 return _a.age>18 }) console.log(_arr) //输出一个数组,数组中的对象为年龄大于18的李四和王五
var arr = [ {name:"张三",age:12}, {name:"李四",age:19}, {name:"赵六",age:15}, ] let _arr = arr.reduce(function(_a,_b,_c,_d){ return _a+_b.age //返回数组中年龄的累加值 })
由上可见reduce()方法用于计算,将数组进行累加,而filter()和map()都不会影响原数组,都会返回一个新的数组
filter和map()的区别是什么呢?
let a = [1, 2, 3, 4, 5, 6] let newA = a.filter((x) => { if (x > 4) { return x } }) console.log(a); //(6) [1, 2, 3, 4, 5, 6] console.log(newA); //(2)[5,6]
let a = [1, 2, 3, 4, 5, 6] let newA = a.filter((x) => { return x + '个' }) console.log(a); //(6) [1, 2, 3, 4, 5, 6] console.log(newA); //(2)[5,6]
let a = [1, 2, 3, 4, 5, 6] let newA = a.map((x) => { if (x > 4) { return x } }) // console.log(a); //(6) [1, 2, 3, 4, 5, 6] console.log(newA); //(6) [undefined, undefined, undefined, undefined, 5, 6]
let a = [1, 2, 3, 4, 5, 6] let newA = a.map((x) => { return x + '个' }) console.log(a); //(6) [1, 2, 3, 4, 5, 6] console.log(newA); //(6) ['1个', '2个', '3个', '4个', '5个', '6个']