问题描述
通常我写的东西都是......
if(x == 1){doSomething()}
...这就是我在所有JS发现中看到它的方式我已经找到了这么多
远。
但是我看到了简写(? )对于同样的事情(?),像这样...
(x == 1)? doSomething()
....和其他几个替代方法。
它们是否记录在某处?我有点像他们,但他们是否支持通常的浏览器团队?
?或者使用它们是愚蠢
因为它们是条纹/马虎?
Thnx提前:)
Usually I write something like ...
if (x==1) { doSomething() }
.... and that''s how I see it in all the JS references I''ve found so
far.
But I have seen shorthand (?) for the same thing (?), like this ...
(x==1) ? doSomething()
.... and several other "alternate" methods.
Are they documented somewhere? I kinda like them, but are they
supported in the usual gang of browsers? or is it stupid to use them
because they are fringe/sloppy?
Thnx in advance :)
推荐答案
这通常被称为三元表达式你的例子是
错过了它的第三部分。
条件?true:false
是构造。如果条件为真则真实部分执行
,如果为假则执行错误部分。
That is commonly called a "ternary expression" and your example is
missing the third part of it.
condition?true:false
Is the construct. If the condition is true then the true part gets
executed, if it is false then the false part gets executed.
三元运算符没有什么愚蠢的。
-
Randy
机会有利于准备好的心灵
comp.lang.javascript常见问题 -
Javascript最佳实践 -
条件?expression1:expression2
如果条件为真,运算符_returns_ expression1,
否则返回expression2。
condition?expression1:expression2
The operator _returns_ expression1 if the condition is true,
otherwise it returns expression2.
http://msdn2.microsoft.com/en-us/library/be21c7hw.aspx
条件?expression1:expression2
运算符_returns_ expression1如果条件为真,
否则返回expression2。
condition?expression1:expression2
The operator _returns_ expression1 if the condition is true,
otherwise it returns expression2.
是的,但无视使用,
或没有结果值,
它可以是和经常使用
只是执行其中一个表达式:
(a> 27.3)?警告(''high''):警报(''低'');
-
Evertjan。
荷兰。
(请将我的电子邮件地址中的x'变为点数)
True, but disregarding the use of,
or in absense of a result value,
it can be and often is used
simply to execute one of those expressions:
(a>27.3) ? alert(''high'') : alert(''low'');
--
Evertjan.
The Netherlands.
(Please change the x''es to dots in my emailaddress)
这篇关于简写语法参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!