使用 if 语句设置 javascript 变量——“var = x"应该在 IF 内部还是外部? [英] setting a javascript variable with an if statement -- should the 'var = x' be inside or outside the IF?
问题描述
这可能是一个基本问题,但我很难找到答案.
This may be a basic question but I'm having difficulty finding an answer.
您想根据 var A 设置 var B
You want to set var B based on var A
你愿意吗
var B = if(A == "red"){"hot"}else{"cool"}
我认为这行不通.
我想你可以做到
if(A == "red"){var B = "hot"}else{var B = "cool"}
这看起来不是特别优雅.我的意思是,为了清楚起见,我更喜欢以 var b = .... 开头的内容.
This doesn't seem particularly elegant. I mean I would prefer something that starts with var b = .... just for clarity's sake.
推荐答案
完美使用三元组
var B = (A ==="red") ? "hot":"cool";
如果为真,三元表达式将始终返回第一个值,否则返回第二个值.非常适合一次性 if/else 语句,但如果您遇到更多嵌套条件,请务必使用传统的 if/else 块以提高可读性.
Ternary expressions will always return the first value if true, the second value if not. Great for one-off if/else statements, but if you get into more nested conditions, be sure to use the traditional if/else blocks for readability.
这篇关于使用 if 语句设置 javascript 变量——“var = x"应该在 IF 内部还是外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!