检查 JS 变量是否不为 null 和 true

Check JS variable for both not null and true

本文关键字:null true JS 变量 是否 检查      更新时间:2023-09-26

检查javascript变量是否既不为空又为真的最佳方法是什么?

例如,假设我有以下代码:

var trueVar = true; 
var falseVar = false; 
function checkNotNullAndTrue(someVar) {
    if (someVar != null && someVar) {
        return 1; 
    } else {
        return 0;
    }
}

checkNotNullAndTrue(trueVar) 应返回 1。

checkNotNullAndTrue(falseVar) 应返回 0。

checkNotNullAndTrue(someUndefinedVariable)也应该返回0。

这是最好的方法还是有更好的方法?

有点

奇怪的问题,因为null是假的。

return x === true; // not null and 'true';
return x; // return truthy value if x not null and truthy; falsy otherwise
return !!x; // return true if x not null and truthy, false otherwise
return +!!x; // return 1 if x not null and truthy, 0 otherwise 

!!x!(!x)一样,把x投为真或假然后否定,然后第二次否定。要么是黑客,要么是与Boolean(x)相同的模式,具体取决于您的世界观。

+<boolean>会将布尔值转换为数字 1 或 0。

无论如何,有人要求一个神秘的答案,而"true"使用了很多不必要的字符,所以这里是:

return +!!(x === ([!![]]+[])); // 1 if x not null and true; 0 otherwise

只需使用严格相等运算符 ( === ):

如果操作数严格相等,则标识运算符返回true [...] 且没有类型转换。

function checkNotNullAndTrue(v) {
    return v === true ? 1 : 0;
}

function checkNotNullAndTrue(v) {
    return +(v === true);
}

为什么黑客的东西不起作用,有时:

// djechlin's part
write(+!!1);                           // 1 obviously not true
write(+!![]);                          // 1 obviously not true
// quentin's part
function test (valid_variable_name) {
    if (valid_variable_name) {
        return 1;
    }
    return 0;
}
write(test(1));                        // 1 obviously not true
write(test([]));                       // 1 obviously not true
// my part
var v = true;
write(+(v === true));                  // 1 true (the only one, that would work!)
write(+(1 === true));                  // 0 false, works
write(+([] === true));                 // 0 false, works
function write(x) {
    document.write(x + '<br>');
}

由于您在示例中提到的null(和 undefined)不是真值,因此测试它们是多余的。

if (valid_variable_name) {
    return 1;
}
return 0;

。就足够了。

。或者if (valid_variable_name === true)是否要测试true而不是任何真实值。