es6新特性 map reduce filter

-------------------------- 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));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值