繁体   English   中英

获取forEach的boolean返回值

[英]Get boolean return value of forEach

我有一个 forEach 循环,其中有一个 find function 。 仅当所有循环的查找函数都返回 true 时,我想在执行 forEach 后获得 boolean 值。 如何才能做到这一点?

const items = ['apple','orange','banana'];
items.forEach((item)=>{
const value = !!items?.find((element)=>element==='apple')
console.log(value) // true, false, false -> return of forEach should be false
})
const items = ['apple','apple','apple'];
items.forEach((item)=>{
const value = !!items?.find((element)=>element==='apple')
console.log(value) // true, true, true -> return of forEach should be true
})

类似的东西

isAllTruthy = items.forEach((item)=>{
return !!items?.find((element)=>element==='apple')

})

这给出了未定义的返回值,我该如何处理

您需要将Array#map用于检查结果。 这允许为数组的每个项目返回一个值。

 const items = ['apple', 'orange', 'banana'], result = items.map(s => s === 'apple'); console.log(result);

如果您想获得单个 boolean 值,您可以使用Array#every

 console.log(['apple', 'orange', 'banana'].every(s => s === 'apple')); console.log(['apple', 'apple', 'apple'].every(s => s === 'apple'));

像这样使用.every

const items = ["apple", "orange", "banana"];
let value = items.every((item) => item === "apple");
console.log(value); // false

const items2 = ["apple", "apple", "apple"];
value = items2.every((item) => item === "apple");
console.log(value); // true

您只能使用 map 数组方法获取返回 boolean 值

 const items = ['apple','orange','banana']; console.log(items.map((e)=> e === 'apple'))

无论您的返回语句如何,forEach 都返回 undefined array.forEach

因此,如果您需要一个可以使用的返回值,array.map() 或 for 循环或任何其他方法都可以让您返回自定义值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM