1、map的用法
定义:原数组被“映射”成对应新数组
代码示例:
var users = [
{name: "张含韵", "email": "zhang@email.com"},
{name: "江一燕", "email": "jiang@email.com"},
{name: "李小璐", "email": "li@email.com"}
]; var emails = users.map(user=> { return user.email; });
2、filter的用法
定义:过滤器
代码示例:
var devices = [];
var curList =[
{id:,name:""},
{id:,name:""},
{id:,name:""},
{id:,name:""}
]
var allList =[
{id:,name:"",title:"嘻嘻0"},
{id:,name:"",title:"嘻嘻1"},
{id:,name:"",title:"嘻嘻2"},
{id:,name:"",title:"嘻嘻3"},
{id:,name:"",title:"嘻嘻4"},
{id:,name:"",title:"嘻嘻5"}
]
allList.forEach(allItem =>{
var foo = curList.filter(curItem =>{return allItem.id == curItem.id})[];
//返回满足条件的数组[{id:*,name:"***",title:"****"}] ,取下标为0的值,即返回满足条件的对象
if(foo){
devices.push({productid:allItem.id, name:allItem.name,title:allItem.title});
}
})
console.log(devices)
filter内部函数判断是否满足条件,满足条件即返回该下标的值并集合成数组。
3、forEach的用法
定义:遍历
代码示例同上。
这是两者的结合使用。
当然上面示例的实现方式有点牵强,其实还有更简便和更好理解的实现方式。以下我就不一一赘述,仅记录用来自我总结和参照。
allList.forEach(allItem =>{
curList.forEach(curItem =>{
if(allItem.id == curItem.id){
devices.push({productid:allItem.id, name:allItem.name,title:allItem.title});
}
}) })
console.log(devices)
}
这样的实现方式也可以提取和组合相同的部分。