[英]Weird behavior with expressions JavaScript
有人可以向我解釋為什么會這樣嗎? 如果有人知道這個行為名稱,請編輯標題。
使用此代碼:
const arr = ['RIPA'], varB = "RIPB";
let _params;
_params && Array.isArray(_params) ? arr.push(..._params) :
arr.push(_params);
_params && console.log("I will never appear");
varB && console.log("I will appear");
arr.push(varB);
console.log('array',arr);
console.log("Type of the _params --> ", typeof _params);
輸出:
array [ 'RIPA', undefined, 'RIPB' ]
Type of the _params --> undefined
jsBIN: https ://jsbin.com/bawepasivo/edit ? js,console
repl.it: https://repl.it/GaHX
如果undefined
_params
,如果&&
表達式返回第一個false和最后一個_params
值,則執行第二個表達式的可能性如何。
false && false ? never executed : _params is undefined
_params && Array.isArray(_params) ? arr.push(..._params) : arr.push(_params);
另一種方式:
if (_params && Array.isArray(_params)) { // (false && false) === false
arr.push(..._params); // it will be never executed
} else {
arr.push(_params); // _params is undefined
}
你的表達式執行如下:
(_params && Array.isArray(_params)) ? arr.push(..._params) : arr.push(_params);
但你的意思可能就是:
_params && (Array.isArray(_params) ? arr.push(..._params) : arr.push(_params));
你只需要添加括號。
let _params; // undefined
_params && Array.isArray(_params) ?
是false
,所以被調用的代碼是arr.push(_params);
,導致arr.push(undefined);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.