简体   繁体   中英

Easiest way to check for a truthy value in JavaScript array

I have an array, and I want to check if any member is truthy. I've tried looping over the array to check for falsy values:

typeof val !== 'undefined' && val !== null && val != 0

...but this seems needlessly verbose for something so simple, and error prone.

如果要测试真实成员,只需将他们作为布尔值进行测试,即可确定其真实性。

const isAnyTruthy = array.some(Boolean)

Array.some(Boolean) . Check out this fiddle .

Another way of doing it is use !! to check the truthy of the value.

const haveTruthyValue = arr.some(x => !!x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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