1 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
您正在尋找some方法:
return superhero.group &&
superhero.group.items &&
superhero.group.items.some(({id}) => id === "1517");
或者如果您在 ES5 中需要它:
return superhero.group &&
superhero.group.items &&
superhero.group.items.some(function(item) {
return item.id === "1517";
});
some為數(shù)組中的每個(gè)條目調(diào)用一次回調(diào),并true在回調(diào)第一次返回真值時(shí)返回,或者false在回調(diào)從未返回真值時(shí)返回(包括數(shù)組中根本沒(méi)有條目)。也就是說(shuō),它檢查數(shù)組中的“某些”(實(shí)際上是“任何”)項(xiàng)是否與回調(diào)表示的謂詞匹配。
這是條件為真和為假時(shí)的示例(在 ES2015+ 中):
function check(superhero) {
return superhero.group &&
superhero.group.items &&
superhero.group.items.some(({id}) => id === "1517");
}
function test(superhero, expect) {
const result = check(superhero);
console.log(`Checking ${JSON.stringify(superhero)}: ${result} <= ${!result === !expect ? "OK" : "ERROR"}`);
}
test({group: {items: [{id: "1"}, {id: "1517"}, {id: "9999"}]}}, true);
test({group: {items: [{id: "1"}, {id: "2"}, {id: "3"}]}}, false);
1“真值”——“真”值是指任何不“假”的值。甲falsy值是一個(gè)值,該值的計(jì)算結(jié)果為false作為一個(gè)條件(如使用時(shí)if (x))。虛假值是0, "", null, undefined, NaN, 當(dāng)然還有false。
添加回答
舉報(bào)