Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - 使用if-else速记时省略第二个表达式(Omitting the second expression when using the if-else shorthand)

Can I write the if else shorthand without the else ?(if else没有else我可以写if else速记吗?)

var x=1; x==2 ? dosomething() : doNothingButContinueCode(); I've noticed putting null for the else works (but I have no idea why or if that's a good idea).(我注意到将else设置为null可以使其他作品有效(但是我不知道为什么或如果那是个好主意)。) Edit: Some of you seem bemused why I'd bother trying this.(编辑:你们中有些人似乎感到困惑,为什么我要尝试这个。) Rest assured it's purely out of curiosity.(请放心,这完全是出于好奇。) I like messing around with JavaScript.(我喜欢弄乱JavaScript。)   ask by Nikki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you have is a fairly unusual use of the ternary operator .(您所拥有的是三元运算符的一种非常不寻常的用法。)

Usually it is used as an expression, not a statement, inside of some other operation, eg:(通常,它在某些其他操作中用作表达式,而不是语句,例如:) var y = (x == 2 ? "yes" : "no"); So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:(因此,出于可读性考虑(因为您正在做的事很不寻常),并且由于它避免了您不希望的“其他”情况,我建议:) if (x==2) doSomething();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...