[英]JavaScript conditional statement with check for empty returns string
在 JavaScript 中,您可以檢查變量是否具有這樣的值
if (strValue) {
//do something
}
今天我遇到了一些超出我理解的事情,我使用它的條件沒有按預期工作。 我有一些 JavaScript 代碼,看起來類似於下面的代碼段。
var blnX = false;
var intX = 3;
var strX = "2021-03-25T13:53:13.259352Z";
function test(blnValue, intValue, strValue) {
return !blnValue && (intValue == 2 || ((intValue == 3 || intValue == 4) && strValue));
}
var result = test(blnX, intX, strX);
在這一點上,我預計result
是true
,但它包含"2021-03-25T13:53:13.259352Z"
。
當我像下面這樣更改return
語句時,
return (((intValue == 3 || intValue == 4) && strValue) || intValue == 2) && !blnValue;
或者像這樣,
return !blnValue && (intValue == 2 || (strValue && (intValue == 3 || intValue == 4)));
然后它確實返回true
。
當我從上面的代碼片段中更改 function 時,它會更加混亂,如下所示,它確實像預期的那樣工作。
function test(blnValue, intValue, strValue) {
if (!blnValue && (intValue == 2 || ((intValue == 3 || intValue == 4) && strValue)))
return true;
return false;
}
有人可以向我解釋為什么第一個 function 中使用的return
語句的條件沒有返回預期的 boolean 值嗎?
你只需要了解如何||
或&&
工作。
2 && 3
將返回3
,因為如果左操作數為真,則返回右操作數。 就這樣。
它在if
中有效,因為3
是真實的,所以
if(2 && 3) {
console.log("bip"); // will be displayed.
}
真/假和 boolean 值是兩個不同的東西。
一些閱讀:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR
||
實際上是合並運算符,而不是邏輯 OR。 它返回其操作數的第一個非假值,否則返回最后一個值
在 Javascript 中,表達式並不總是返回true
或false
。 他們返回他們評估的最后一個東西的值。
將任何內容轉換為true
或false
的一個簡單技巧是使用雙感嘆號。 一個感嘆號將與表達的真實性相反,因此兩個感嘆號會將其切換回其原始 boolean 等效項。
請參閱示例代碼。
const a = 'hello' const b = 1 console.log(b && a) // outputs 'hello' since 'a' was the last evaluated thing console.log(b || a) // outputs 1 since 'b' was truthy and no need to evaluate a console.log(!!(b || a)) // outputs true since !! quickly converts to boolean
也許它可能有助於逐步考慮如何return;blnValue && (intValue == 2 || ((intValue == 3 || intValue == 4) && strValue));
被評估:
/*
* GIVEN:
* blnValue = blnX = false;
* intValue = intX = 3;
* strValue = strX = "2021-03-25T13:53:13.259352Z";
*/
/*0*/ !blnValue && (intValue == 2 || ((intValue == 3 || intValue == 4) && strValue));
/*1*/ !false && (3 == 2 || (( 3 == 3 || 3 == 4) && '2021-03-25T13:53:13.259352Z'));
/*2*/ true && (false || ((true || false) && '2021-03-25T13:53:13.259352Z'));
/*3*/ true && (false || (true && '2021-03-25T13:53:13.259352Z'));
/*4*/ true && (false || '2021-03-25T13:53:13.259352Z');
/*5*/ true && '2021-03-25T13:53:13.259352Z';
/*6*/ '2021-03-25T13:53:13.259352Z';
另請注意:
const a = true && '2021-03-25T13:53:13.259352Z';
const b = '2021-03-25T13:53:13.259352Z' && true;
console.log(a); // -> '2021-03-25T13:53:13.259352Z'
console.log(b); // -> true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.