简体   繁体   中英

Simplify simple ternary expression

I want to validate undefined attributes from an object so I use ternary like this

item.subitem ? item.subitem.toString() : ''

Is there any way to simplify this expression using || or && ?

It's simple:

item.subitem && item.subitem.toString() || ''

Or simply like:

(item.subitem || '').toString()

OR,

''+(item.subitem || '')

If you can use optional chaining, then it can be even more simple:

item.subitem?.toString()

See this post for more detail.


As @Thomas mentioned in comment , you can also use an array and convert to a string:

[item.subitem].toString();

This should clear how it will work:

[].toString(); // ''
[undefined].toString(); // ''
['foo'].toString(); // 'foo'
['foo', 'bar'].toString(); 'foo,bar'

是的你可以

(item.subitem || '').toString()

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