带有函数的 JavaScript 三元运算符示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10323829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript ternary operator example with functions
提问by Evik James
I am using jQuery 1.7.1
我正在使用 jQuery 1.7.1
I am just starting to use the JavaScript ternary operator to replace simple if/else statements. I have done so successfully in several places. I was surprised when I successfully made something else work when I thought for sure it wouldn't, but I tried anyway.
我刚刚开始使用 JavaScript 三元运算符来替换简单的 if/else 语句。我已经在几个地方成功地做到了这一点。当我认为肯定不会的时候,我成功地使其他东西起作用时我感到惊讶,但我还是尝试了。
Here's the original statement:
以下是声明原文:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
if (IsChecked == true){
removeItem($this);
} else {
addItem($this);
}
}
Here's the same function using the ternary operator:
这是使用三元运算符的相同函数:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
(IsChecked == true) ? removeItem($this) : addItem($this);
}
I was surprised because all of the examples I saw being used were merely setting variables like this:
我很惊讶,因为我看到使用的所有示例都只是设置这样的变量:
x = (1 < 2) ? true : false;
My question is whether this is "normal" use and will it work in most versions of JavaScript? Where will it fail? Are there other less obvious uses for it?
我的问题是这是否是“正常”使用,它是否适用于大多数 JavaScript 版本?它会在哪里失败?它还有其他不太明显的用途吗?
UPDATE -- Thanks for the "real world" advice!!!
更新——感谢“现实世界”的建议!!!
I am using this as my function:
我使用它作为我的功能:
function updateItem() {
$this = $(this);
$this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}
回答by JonnyReeves
Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best...
呵呵,你的问题中有一些非常令人兴奋的三元语法用法;我最喜欢最后一张。。。
x = (1 < 2) ? true : false;
The use of ternary here is totally uncessesary - you could simply write
在这里使用三元是完全不必要的 - 你可以简单地写
x = (1 < 2);
Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, therefore you can express:
同样,三元语句的条件元素始终被评估为布尔值,因此您可以表示:
(IsChecked == true) ? removeItem($this) : addItem($this);
Simply as:
简单来说:
(IsChecked) ? removeItem($this) : addItem($this);
Infact, I would also remove the IsChecked
temporary as well which leaves you with:
事实上,我也会删除IsChecked
临时的,这给你留下了:
($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);
As for wether this is acceptable syntax, it sure is! It's a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)
至于这是否是可接受的语法,它肯定是!这是将四行代码缩减为一行而不影响可读性的好方法。我给你的唯一建议是避免在同一行嵌套多个三元语句(这种方式很疯狂!)
回答by Surreal Dreams
The ternary style is generally used to save space. Semantically, they are identical. I prefer to go with the full if/then/else syntax because I don't like to sacrifice readability - I'm old-school and I prefer my braces.
三元样式一般用于节省空间。在语义上,它们是相同的。我更喜欢使用完整的 if/then/else 语法,因为我不喜欢牺牲可读性——我是老派,我更喜欢我的大括号。
The full if/then/else format is used for pretty much everything. It's especially popular if you get into larger blocks of code in each branch, you have a muti-branched if/else tree, or multiple else/ifs in a long string.
完整的 if/then/else 格式几乎用于所有内容。如果您在每个分支中进入更大的代码块,您有一个多分支的 if/else 树,或者一个长字符串中的多个 else/if,它就会特别受欢迎。
The ternary operator is common when you're assigning a value to a variable based on a simple condition or you are making multiple decisions with very brief outcomes. The example you cite actually doesn't make sense, because the expression will evaluate to one of the two values without any extra logic.
当您根据一个简单的条件为变量赋值时,或者您正在做出具有非常简短结果的多个决策时,三元运算符很常见。您引用的示例实际上没有意义,因为该表达式将计算为两个值之一,而无需任何额外的逻辑。
Good ideas:
好主意:
this > that ? alert(this) : alert(that); //nice and short, little loss of meaning
if(expression) //longer blocks but organized and can be grasped by humans
{
//35 lines of code here
}
else if (something_else)
{
//40 more lines here
}
else if (another_one) /etc, etc
{
...
Less good:
不太好:
this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.
if(this != that) //Ternary would be done by now
{
x = this;
}
else
}
x = this + 2;
}
A really basicrule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.
一个非常基本的经验法则 - 你能理解整件事还是更好地理解?三元没问题。否则展开。
回答by Jeff B
There is nothing particularly tricky about the example you posted.
您发布的示例没有什么特别棘手的地方。
In a ternary operator, the first argument (the conditional) is evaluated and if the result is true
, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.
在三元运算符中,计算第一个参数(条件),如果结果为true
,则计算并返回第二个参数,否则计算并返回第三个参数。每个参数都可以是任何有效的代码块,包括函数调用。
Think of it this way:
可以这样想:
var x = (1 < 2) ? true : false;
Could also be written as:
也可以写成:
var x = (1 < 2) ? getTrueValue() : getFalseValue();
This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:
这是完全有效的,这些函数可以包含任意代码,无论是否与返回值有关。此外,三元运算的结果不必分配给任何东西,就像函数结果不必分配给任何东西一样:
(1 < 2) ? getTrueValue() : getFalseValue();
Now simply replace those with any arbitrary functions, and you are left with something like your example:
现在只需将它们替换为任意函数,您就会得到类似于您的示例的内容:
(1 < 2) ? removeItem($this) : addItem($this);
Now your last example really doesn't need a ternary at all, as it can be written like this:
现在你的最后一个例子真的根本不需要三元,因为它可以这样写:
x = (1 < 2); // x will be set to "true"
回答by Sam W
If you're going to nest ternary operators, I believe you'd want to do something like this:
如果你要嵌套三元运算符,我相信你会想要做这样的事情:
var audience = (countrycode == 'eu') ? 'audienceEU' :
(countrycode == 'jp') ? 'audienceJP' :
(countrycode == 'cn') ? 'audienceCN' :
'audienceUS';
It's a lot more efficient to write/read than:
写/读比:
var audience = 'audienceUS';
if countrycode == 'eu' {
audience = 'audienceEU';
} else if countrycode == 'jp' {
audience = 'audienceJP';
} else if countrycode == 'cn' {
audience = 'audienceCN';
}
As with all good programming, whitespace makes everything nice for people who have to read your code after you're done with the project.
与所有优秀的编程一样,对于在您完成项目后必须阅读您的代码的人来说,空格使一切变得美好。
回答by Bart?omiej Zalewski
I would also like to add something from me.
我也想从我这里补充一些东西。
Other possible syntax to call functions with the ternary operator, would be:
使用三元运算符调用函数的其他可能语法是:
(condition ? fn1 : fn2)();
It can be handy if you have to pass the same list of parameters to both functions, so you have to write them only once.
如果您必须将相同的参数列表传递给两个函数,这会很方便,因此您只需编写一次。
(condition ? fn1 : fn2)(arg1, arg2, arg3, arg4, arg5);
You can use the ternary operator even with member function names, which I personally like very much to save space:
您甚至可以使用成员函数名称使用三元运算符,我个人非常喜欢它以节省空间:
$('.some-element')[showThisElement ? 'addClass' : 'removeClass']('visible');
or
或者
$('.some-element')[(showThisElement ? 'add' : 'remove') + 'Class']('visible');
Another example:
另一个例子:
var addToEnd = true; //or false
var list = [1,2,3,4];
list[addToEnd ? 'push' : 'unshift'](5);
回答by Himanshu Tiwari
I know question is already answered.
我知道问题已经回答了。
But let me add one point here. This is not only case of true or false. See below:
但让我在这里补充一点。这不仅是真假的情况。见下文:
var val="Do";
Var c= (val == "Do" || val == "Done")
? 7
: 0
Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.
这里如果 val 是 Do 或 Done 那么 c 将是 7 否则它将为零。在这种情况下,c 将为 7。
This is actually another perspective of this operator.
这其实是这个运营商的另一个角度。