簡體   English   中英

檢查JS變量是否為非null和true

[英]Check JS variable for both not null and true

檢查javascript變量是否不是null和true的最佳方法是什么?

因此,例如,假設我有以下代碼:

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。

這是執行此操作的最佳方法,還是有更好的方法?

只需使用嚴格相等運算符( ===

如果操作數嚴格相等且沒有類型轉換,則標識運算符將返回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是虛假的,所以有點奇怪的問題。

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強制轉換為true或false 並取反 ,然后第二次取反。 hack或與Boolean(x)相同的模式取決於您的世界觀。

+<boolean>會將+<boolean>轉換為數字1或0。

無論如何,有人請求一個神秘的答案,而“ true”使用了很多不必要的字符,因此這里是:

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

由於null (以及在示例中提到的undefined )不是真實值,因此對其進行測試是多余的。

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

… 足夠了。

…或if (valid_variable_name === true)如果要測試true而不是任何true值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM