1.filter()用法详解
应用场景1:假定有一个对象数组A,获取数组中指定类型的对象放到B数组中。
var products = [
{
name: "cucumber",
type: "vegetable"
},
{
name: "apple",
type: "fruit"
},
{
name: "orange",
type: "fruit"
}
];
var filters = products.filter(function(item) {
return item.type == "fruit";
});
console.log(filters);
//结果:[{name: “apple”, type: “fruit”},{name: “orange”, type: “fruit”}]
应用场景2:假定有一个对象数组A,过滤掉不满足一下条件的对象,条件:水果 ,价格小于10,数量大于0。
var products = [
{
name: "cucumber",
type: "vegetable",
quantity: 10,
price: 5
},
{
name: "apple",
type: "fruit",
quantity: 0,
price: 5
},
{
name: "orange",
type: "fruit",
quantity: 1,
price: 2
}
];
var filters = products.filter(function(item) {
//使用&符号将条件链接起来
return item.type === "fruit" && item.quantity > 0 && item.price < 10;
});
console.log(filters);
//结果:[{name: “orange”, type: “fruit”, quantity: 1, price: 2}]
应用场景3:假定有对象A和数组B,根据A中id值,过滤掉B中不符合的数据。
var post = { id: 1, title: "A" };
var comments = [
{ postId: 3, content: "CCC" },
{ postId: 2, content: "BBB" },
{ postId: 1, content: "AAA" }
];
function commentsPost(post, comments) {
return comments.filter(function(item) {
return item.postId == post.id;
});
}
console.log(commentsPost(post, comments));
//结果:[{postId: 1, content: “AAA”}],返回的是数组
注意:filter和find区别:filter返回的是数组,find返回的是对象。
2.find()用法详解
应用场景1:假定有一个对象数组A,找到符合条件的对象
var users = [
{ name: "jack", age: 12 },
{ name: "alex", age: 15 },
{ name: "eva", age: 20 }
];
var user = users.find(function(item) {
return (item.name = "eva");
});
console.log(user);
//结果:{ name: “eva”, age: 20 }
注:find()找到第一个元素后就不会在遍历其后面的元素,所以如果数组中有两个相同的元素,他只会找到第一个,第二个将不会再遍历了。
应用场景2:假定有一个对象数组A,根据指定对象的条件找到数组中符合条件的对象。
var post = { id: 1, title: "AAA" };
var comments = [
{ postId: 3, content: "CCC" },
{ postId: 2, content: "BBB" },
{ postId: 1, content: "AAA" }
];
function commentsPost(post, comments) {
return comments.find(function(item) {
return item.postId == post.id;
});
}
console.log(commentsPost(post, comments));
//结果:{postId: 1, content: “AAA”},返回的是对象