-------------------------- map (一一对应return出来) ----------------------------------
let arr=[68,55,12,32];
let arr2=arr.map(function(item){
if(item>=60){
return '及格'
}else{
return '不及格'
}
})
-------------------------- reduce(求和或者平均数) ----------------------------------
let res=arr.reduce(function(tmp,item,index){
if(index==arr.length-1){
return (tmp+item)/arr.length; //一次一次加
}else{
return tmp+item; //加到最后一次返回数据
}
})
-------------------------- filter(过滤数组) ----------------------------------
// es6 filter
var filtered2 = porducts.filter(function(product){
return product.type === "vegetable";
})
// console.log(filtered2);
/** 场景2
*
- 假定有一个对象数组(A),过滤掉不满足以下条件的对象
- 条件: 蔬菜 数量大于0,价格小于10
*/
var products = [
{name:"cucumber",type:"vegetable",quantity:0,price:1},
{name:"banana",type:"fruit",quantity:10,price:16},
{name:"celery",type:"vegetable",quantity:30,price:8},
{name:"orange",type:"fruit",quantity:3,price:6}
];
products = products.filter(function(product){
return product.type === "vegetable"
&& product.quantity > 0
&& product.price < 10
})
console.log(products);
/** 场景3
*
- 假定有两个数组(A,B),根据A中id值,过滤掉B数组不符合的数据
*/
var post = {id:4,title:"Javascript"};
var comments = [
{postId:4,content:"Angular4"},
{postId:2,content:"Vue.js"},
{postId:3,content:"Node.js"},
{postId:4,content:"React.js"},
];
function commentsForPost(post,comments){
return comments.filter(function(comment){
return comment.postId === post.id;
})
}
console.log(commentsForPost(post,comments));
-------------------------- forEach(遍历数组) ----------------------------------
-------------------------- find(查找功能) ----------------------------------
// es6 find
user = users.find(function(user){
return user.name === "Alex";
})
// console.log(user);
/** 场景2
*
- 假定有一个对象数组(A),根据指定对象的条件找到数组中符合条件的对象
*/
var posts = [
{id:3,title:"Node.js"},
{id:2,title:"React.js"}
];
var comment = {postId:1,content:"Hello World!"};
function postForComment(posts,comment){
return posts.find(function(post){
return post.id === comment.postId;
})
}
console.log(postForComment(posts,comment));