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"},返回的是對象
