首先理解二维数组/对象指什么
var books = [
{id:'1',name:'JAVA',author:'s0nei',price:6},
{id:'2',name:'HTML',author:'d1iber',price:7},
{id:'3',name:'JS',author:'j1lion',price:8},
{id:'4',name:'C',author:'s0nei',price:9}
]
目标1:得到所有id的值
取出数组对象中对象的值
var res = []
books.forEach(e=>{res.push(e.id)})
//map 要求每次遍历都有返回值,换句话说,如果第三本书没有id,最终的res长度还是那么多,只是第三个位置空着
var res = books.map(e=>e.id)//是以下的简写
var res = books.map(e=>{return e.id})
目标2 :得到author是s0nei的对象
取出数组对象中对象
var res = []
books.forEach(e=>{if(e.author==='s0nei')res.push(e)})
//filter 要求返回值是布尔型,如果是true,就把这一条条目完整地拷贝下来
var res = books.filter(e=>e.author==='s0nei')//是以下的简写
var res = books.filter(e=>{if(e.author==='s0nei')return true})
以上两种个都有局限性,因此使用reduce
标准格式:
books.reduce((t,v)=>{
return t
})
目标1:得到所有id的值
books.reduce((t,v)=>{
t.push(v.id)
return t
},[])
目标2 :得到author是s0nei的对象
books.reduce((t,v)=>{
if(v.author==="s0nei"){
t = [t,v]
}
return t
})
别的需求也可以用这轻松完成,比如找出s0nei的书名
books.reduce((t,v)=>{
if(v.author==="s0nei"){
t = [...t,v.name]
}
return t
},[])