Looking for a simpler way to check if multiple properties & methods in an object are undefined
Consider the following code:
if(eform[开发者_开发百科funcName] !== undefined){
if(eform[funcName].init !== undefined){
//finally do something
}
}
I'm first checking to see if the eform
object has the property specified by the variable funcName
. If it does, then I need to check whether that property has an init
method.
Is there any way to combine these into a single if
statement? Or perhaps something even more elegant than that?
Using Short-Circuit evaluation:
if (eform[funcName] !== undefined && eform[funcName].init !== undefined)
If eform[funcName]
is undefined the statement if false and eform[funcName].init
is never checked. Depending on preference/readability this following is vaild as well:
if (eform[funcName] && eform[funcName].init)
think that one is better:
if(eform[funcName] !== undefined && eform[funcName].init !== undefined){
//some code
}
if the first condition is false than the second condition wont be checked.
JS has a new, elegant way to achieve this - The Optional Chaining operator
It looks like this:
if (eform?[funcName]?.init !== undefined) {
// do something
}
Works with all modern browsers. But babel has not yet added support for this op natively and throws a compilation error. In that case, babel suggests:
Add @babel/plugin-proposal-optional-chaining (https://git.io/vb4Sk) to the 'plugins' section of your Babel config to enable transformation.
精彩评论