Multiple comparison operators in a JavaScript boolean expression

后端 未结 3 768
不思量自难忘°
不思量自难忘° 2020-12-11 07:34

I\'m trying to check whether the variable y is less than x and greater than z, but this boolean expression is returning false for some reason. Does JavaScript allow boolean

相关标签:
3条回答
  • 2020-12-11 07:39

    Change your test to

    if (x > y && y > z){
    

    When you write (x > y > z), this is equivalent to ((x>y)>z), so you're comparing a boolean (x>y) to z. In this test, true is converted to 1, which isn't greater than 2.

    0 讨论(0)
  • 2020-12-11 07:58

    Try using the logical and operator:

    if (x > y && y > z) {
    

    to guarantee both conditions are true.

    DEMO: http://jsfiddle.net/3sxvy/

    If you need to put this into a function, you could try:

    function compareNumbers(direction) {
        var inOrder = (function () {
            if (direction === "desc") {
                return function (current, before) {
                    return current <= before;
                };
            } else if (direction === "asc") {
                return function (current, before) {
                    return current >= before;
                };
            }
        })();
        var valid = true;
        for (var i = 2; i < arguments.length; i++) {
            if (!inOrder(arguments[i], arguments[i-1])) {
                valid = false;
                break;
            }
        }
        return valid;
    }
    
    if (compareNumbers("desc", 33, 5)) {
        console.log("Good");
    } else {
        console.log("Bad");
    }
    

    DEMO: http://jsfiddle.net/kn6M4/1/

    0 讨论(0)
  • 2020-12-11 07:59

    You want

    if(x > y && y > z){
        alert("x > y > z"); //Nothing happens!
    }
    

    Javascript will try to parse your original statement from left to right and you'll end up comparing z to a boolean value which will then be parsed to a number (0 or 1).

    So your original statement is equivalent to

    if( (x > y && 1 > z) || (x <= y && 0 > z))
    
    0 讨论(0)
提交回复
热议问题