我正在尝试使用javascript ?:语法重写下面的语句。
if(type of someVariable !="undefined"){
someFunction(someVariable);
}else{}这是我当前的尝试,它导致了一个语法错误
typeof someVariable != "undefined" ? someFunction(someVariable) : ;如果有人能告诉我我做错了什么,我将不胜感激。欢迎任何关于防御性编程最佳实践的技巧。
发布于 2013-11-07 10:23:25
?:style (需要:两端的表达式):
typeof(someVariable) != 'undefined' ? someFunction : null;忍者风格:
someVariable !== undefined && someFunction(someVariable);编辑:我不能发誓noop是Javascript中的一个东西,但很明显我错了。切换到null
发布于 2013-11-07 10:26:09
它应该看起来像这样。
someVariable != undefined ? someFunction(someVariable):someOtherfunction(someOtherVarialbe);如果你不想要else语句,而只想把它写成一行,你可以这样做:
if(someVariable != undefined){someFunction(someVariable);}发布于 2013-11-07 10:31:45
即使三元操作控制程序流,我也只在赋值操作或从函数返回值时使用它。
看看这个:Benefits of using the conditional ?: (ternary) operator
https://stackoverflow.com/questions/19826796
复制相似问题