Greater than operator given wrong response inside console.log in javascript

南笙酒味 提交于 2021-02-17 05:33:46

问题


I have tried conditional operator inside console.log(). Less than < returns correct response but greater than > returns wrong response. Why?

    console.log(5<6<7);
    //Output: true

    console.log(7>6>5);
    //output: false

回答1:


The < operator accepts two operands and yields a boolean result. Your code is effectively:

let temp = 7 > 6;
console.log(temp);      // true
let result = temp > 5;
console.log(result);    // false

The reason temp > 5 is false is that true > 5 coerces true to a number (1), and 1 > 5 is false.

Insead, use && if you want a logical AND condition:

console.log(7 > 6 && 6 > 5); // true



回答2:


The lower than and greater than operators are evaluated from left to right (see Operator precedence):

5 < 6 < 7 = (5 < 6) < 7 = true < 7 = 1 < 7 = true

7 > 6 > 5 = (7 > 6) > 5 = true > 5 = 1 > 5 = false

The boolean values (false/true) are converted to integers (0/1) here. ("If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false." (source: MDN))



来源:https://stackoverflow.com/questions/52678596/greater-than-operator-given-wrong-response-inside-console-log-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!