Multiple comparison operators in a JavaScript boolean expression

后端 未结 3 773
不思量自难忘°
不思量自难忘° 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: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/

提交回复
热议问题