简体   繁体   English

奇怪的三元运算符Javascript

[英]Weird ternary operator Javascript

I'm trying to understand how ternary operators work and I came across this example: 我试图了解三元运算符的工作方式,并遇到了以下示例:

b.d >= mystr.length && (function1(b, a), a=0);

What does && mean? 这是什么意思? is it used like an AND operator? 像AND运算符一样使用吗? how does this translate to regular statement? 这如何转化为常规陈述? What does the coma before a=0 mean? a = 0之前的昏迷是什么意思? Thanks! 谢谢!

That's not a ternary. 那不是三元。

Also, the comma inside that grouping operator basically ensures that the group will always return the value of the last expression a=0 , which is 0. 此外,该分组运算符内的逗号基本上可确保该分组始终返回最后一个表达式a=0 ,即0。

That example will always evaluate to either false or 0 (which is falsy). 该示例将始终为false或0(错误)。

Edit: 编辑:

For the sake of completeness, here's a ternary operator: 为了完整起见,下面是一个三元运算符:

a > b ? functionIfTrue() : functionIfFalse();

It is logically identical to: 从逻辑上讲,它等同于:

if ( a > b ){
    functionIfTrue();
} else {
    functionIfFalse();
}

&& is the AND operator. &&是AND运算符。 If the left of it is true, it's evaluate the right side (and return it). 如果左边为真,则评估右边(并返回)。 The , is the comma operator. ,是逗号运算符。 (The comma operator evaluate both its sides, left to right, and return the right side). (逗号运算符从左到右评估其两侧,并返回右侧)。 So this code is like: 所以这段代码就像:

if (b.d>=mystr.lengh) {
 function1(b,a);
 a=0;
}

(Except that your code return 0) (除了您的代码返回0)

(My native language is C , so maybe I'm wrong, but I think that in this case, javascript work like C) (我的母语是C ,所以也许我错了,但是我认为在这种情况下,javascript可以像C一样工作)

The && operator is the logical AND operator. &&运算符是逻辑AND运算符。 It evaluates the expressions from left to right and returns the first falsey value or the value of the last expression.. 它从左到右评估表达式,并返回第一个false值或最后一个表达式的值。

If it gets to the last expression, it returns its value, whatever that is. 如果到达最后一个表达式,则返回其值,无论是什么值。

So: 所以:

var x = (1 < 2) && ( 4 > 3) && 'fred';

sets x to "fred", whereas: x设置为“ fred”,而:

var y = (1 < 2) && 0 && 'fred';

sets y to 0 . y设置为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM