[英]Javascript: Most effecient way to define variable to a function call, or if null to a variable?
Using ternary operator requires two calls to the function. 使用三元运算符需要两次调用该函数。
var colour = (tryAdventurousColour() != null) ? tryAdventurousColour() : 'black';
Possible to do it in 1 line? 可以在1行中完成吗?
EDIT: Fixed syntax EDIT: Like this but better 编辑:固定语法编辑:像这样,但更好
var colour = ( (colour = tryAdventurousColour() ) != null ) ? var color =((colour = tryAdventurousColour())!= null)? colour : 'black';
颜色:'黑色';
Use JavaScript's logical or operator: 使用JavaScript的逻辑或运算符:
var colour = tryAdventurousColour() || 'black';
Your function tryAdventurousColour()
will be executed once. 您的函数
tryAdventurousColour()
将执行一次。 If it returns a "truthy" value then that colour
variable will be assigned to that value, otherwise colour
will be 'black'. 如果返回“真实”值,则该
colour
变量将被分配给该值,否则colour
将为“黑色”。 This fits your scenario perfectly since null
is a "falsy" value. 因为
null
是一个“虚假”值,因此这完全适合您的情况。
In more general terms, the expression a || b
一般而言,表达式
a || b
a || b
returns a
if it can be converted to true (is "truthy"), otherwise it returns b
. a || b
返回a
,如果它可以被转换为true(是“truthy”),否则返回b
。 Note that non-zero numbers, non-empty strings and objects will all be converted to true. 请注意,非零数字,非空字符串和对象都将转换为true。
null
, undefined, 0, "" will all be converted to false. null
,undefined,0,“”将全部转换为false。 (I'm sure somebody will correct me if I've left something out.) (如果我遗漏了一些东西,我敢肯定有人会纠正我的。)
var colour = (tryAdventurousColour()) ? tryAdventurousColour() : 'black';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.