带函数的 JavaScript 三元运算符示例

我使用的是 jQuery 1.7.1

我刚开始使用 JavaScript 三元运算符来替换简单的 if/else 语句。我在好几个地方都做得很成功。当我成功地让别的东西工作时,我感到很惊讶,因为我以为它肯定不会工作,但我还是尝试了。

这是最初的声明:

function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
if (IsChecked == true){
removeItem($this);
} else {
addItem($this);
}
}

下面是使用三元运算符的相同函数:

function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
(IsChecked == true) ? removeItem($this) : addItem($this);
}

我感到惊讶,因为我看到的所有被使用的例子都只是像这样设置变量:

x = (1 < 2) ? true : false;

我的问题是,这是否是“正常”的使用,它是否能在大多数版本的 JavaScript 中工作?它会在哪里失败?它还有其他不那么明显的用途吗?

更新——感谢“真实世界”的建议! ! !

我用这个作为我的功能:

function updateItem() {
$this = $(this);
$this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}
169374 次浏览

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.

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"

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 unnecessary - you could simply write

x = (1 < 2);

Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, and therefore you can express:

(IsChecked == true) ? removeItem($this) : addItem($this);

Simply as:

(IsChecked) ? removeItem($this) : addItem($this);

In fact, I would also remove the IsChecked temporary as well which leaves you with:

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

As for whether 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!)

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.

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.

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 basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.

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.

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.

This is actually another perspective of this operator.

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);