使用==运算符检查变量是否为0 / false / null等以外的任何值?

时间:2014-02-15 10:02:23

标签: javascript variables

function test(variable, check) {

    var check = check || ???;

    if (variable == check) {
        //do stuff
    }
}

我希望此函数检查变量是否为if(variable) return true;将返回true的任何值,例如,任何大于0的数字。我想保留这种简单的格式并使用==运算符,如果可能的话check是特定值,那么为了达到这个目的,我可以将其默认为什么?

我可以用这段代码实现同样的目的:

function test(variable, check) {

    if(check) {

        //check specific value
        if (variable == check) {
            //do stuff
        }

    } else {

        //check isn't set, so accept any truthy values (like 5 or 'string')
        if(variable) {
            //do stuff
        }
    }
}

2 个答案:

答案 0 :(得分:2)

聊了一会后,答案是:

if (check ? check == variable : variable) {
    // do something
}

实际上很明显...... = D

答案 1 :(得分:1)

如果我正确理解了这个问题,你想基本上返回if(variable) true,并检查它是否等于第二个参数?如果是这样,这应该足够了:

function test(variable, check) {
  if(variable == check) return true; //check against the check value
  if(variable) return true; //default check
  return false; //return false otherwise.
}
相关问题