filter()和find()的用法區(qū)別
應(yīng)用場景1:假定有一個對象數(shù)組A,獲取數(shù)組中指定類型的對象放到B數(shù)組中。
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);
//結(jié)果:[{name: "apple", type: "fruit"},{name: "orange", type: "fruit"}]
應(yīng)用場景2:假定有一個對象數(shù)組A,過濾掉不滿足一下條件的對象,條件:水果 ,價格小于10,數(shù)量大于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);
//結(jié)果:[{name: "orange", type: "fruit", quantity: 1, price: 2}]
應(yīng)用場景3:假定有對象A和數(shù)組B,根據(jù)A中id值,過濾掉B中不符合的數(shù)據(jù)。
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));
//結(jié)果:[{postId: 1, content: "AAA"}],返回的是數(shù)組
注意:filter和find區(qū)別:filter返回的是數(shù)組,find返回的是對象。
2.find()用法詳解
應(yīng)用場景1:假定有一個對象數(shù)組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);
//結(jié)果:{ name: "eva", age: 20 }
注:find()找到第一個元素后就不會在遍歷其后面的元素,所以如果數(shù)組中有兩個相同的元素,他只會找到第一個,第二個將不會再遍歷了。
應(yīng)用場景2:假定有一個對象數(shù)組A,根據(jù)指定對象的條件找到數(shù)組中符合條件的對象。
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));
//結(jié)果:{postId: 1, content: "AAA"},返回的是對象
數(shù)組常用方法以及區(qū)別
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。