ES6 filter函数过滤


/*
    有一个对象数组 a ,将a数中对象某个属性的值存储到B数组中
*/ 
var porducts = [
    {name:"cucumber",type:"vegetable"},
    {name:"banana",type:"fruit"},
    {name:"celery",type:"vegetable"},
    {name:"orange",type:"fruit"},
];
// es5
var filteredProducts = [];
for(var i = 0;i < porducts.length; i ++){
    if(porducts[i].type === "fruit"){
        // 如果条件满足就把当前的值推入
        filteredProducts.push(porducts[i])
    }
}
// console.log(filteredProducts)//0: {name: "banana", type: "fruit"}1: {name: "orange", type: "fruit"}length: 2__proto__: Array(0)
// ES6
 var filter2 = porducts.filter(function(porduct){//对porducts数组对象过滤如果porduct.type === "fruit"就return出去,再用一个变量接住
    return porduct.type === "fruit"
})
console.log(filter2)
/*
    需求二
    有一个对象数组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)//0: {name: "celery", type: "vegetable", quantity: 30, price: 8}name: "celery"price: 8quantity: 30type: "vegetable"__proto__: Objectlength: 1__proto__: Array(0)

/*
    需求三:
    有两个数组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))
// 0: {postId: 4, content: "Angular4"}1: {postId: 4, content: "React.js"}length: 2__proto__: Array(0)

如需转载,烦请注明出处:https://www.qdskill.com/javascript/12111.html

发表评论

登录后才能评论