<script> var arr = [ { age:11, name:'aa' }, { age:22, name:'bb' }, { age:33, name:'cc' } ] // map 使用 var age = arr.map((item,index)=>{ console.log(item,index) //数组项,下标 return item.age }) console.log(age) // [11, 22, 33] // es6写法 var ageEs6 = arr.map(item=>item.age) console.log(ageEs6) // [11, 22, 33] // reduce // 累加计算 var ageR = arr.reduce((n,y)=>{ console.log(n, y, y.age) // n:初始值 y:循环项 return n + y.age },0) //第二个参数定义初始值 console.log(ageR) //0 + 11 + 22 + 33 = 66 获取最终结果 // es6写法 var ageRes6 = arr.reduce((n,y)=> n + y.age, 0) console.log(ageRes6) //66
案例:合并数组对象里的子数组
var arr = [ { title:'11', arrChild:[ { name:'a', age:12 } ] }, { title:'22', arrChild:[ { name:'b', age:12 } ] }, { title:'33', arrChild:[ { name:'c', age:12 } ] }, ] let newArr = arr.reduce((a,b)=> a.concat(b.arrChild) ,[]) console.log(newArr);////[{name: "a", age: 12},{name: "b", age: 12},{name: "b", age: 12}]
// filter 过滤 var arrName = arr.filter((item)=>{ return item.name == 'cc' }) var arrName2 = arr.filter(item=> item.name == 'cc') console.log(arrName,arrName2) // [ {age:33,name:'cc'} ] var arrAge = arr.filter(item=> item.age > 20) console.log(arrAge) </script>