JavaScript布尔表达式中的多个比较运算符 [英] Multiple comparison operators in a JavaScript boolean expression

查看:72
本文介绍了JavaScript布尔表达式中的多个比较运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查变量y是否小于x且大于z,但是这个布尔表达式由于某种原因返回false。 JavaScript是否允许像这样简洁地编写布尔表达式?如果是,那么正确的语法是什么?

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 expressions to be written concisely like this? If so, what is the correct syntax?

x = 2;
y = 3;
z = 4;

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


推荐答案

尝试使用逻辑运算符:

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/

这篇关于JavaScript布尔表达式中的多个比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆