我读到JavaScript中的双重管道检查变量是否为假,而undefined
是JavaScript中的假值,例如。
这意味着如果值为falsey(例如0,"",null,undefined(请参阅 也是JavaScript中的所有虚假值)),它将被视为false; 否则它被视为真实。
所以我尝试了这一点,发现undefined确实没有被评估为假,而是抛出一个错误:
let elemContent = document.getElementById('content');
let a = null;
let b = 2;
elemContent.innerHTML += a || 'ok'; // "ok"
elemContent.innerHTML += b || 'ok'; // "2"
elemContent.innerHTML += whatever || 'ok'; // "ERROR: whatever is not defined"
undefined
是否是JavaScript中的假值,或者如何理解这一矛盾?
答案 0 :(得分:36)
因为在您的代码中,whatever
不仅undefined
而且未声明
要避免此错误,您可以执行以下操作:
let elemContent = document.getElementById('content');
let a = null;
let b = 2;
elemContent.innerHTML += a || 'ok'; // "ok"
elemContent.innerHTML += b || 'ok'; // "2"
elemContent.innerHTML += (typeof whatever !== 'undefined' && whatever) || 'ok3'; // "ok3"
答案 1 :(得分:12)
let whatever = undefined
确实是假的,但在声明声明之前使用变量是JavaScript中的一个错误。
在某处添加INSERT INTO T3 (ID, PNo, MM, CP, Flag, Name)
SELECT T2.ID, T2.PNo, T2.MM, T2.CP, ?, "A"
FROM T2
WHERE T2.ID IN (SELECT ID FROM T1 WHERE Flag = "A");
以查看您期望的行为。
答案 2 :(得分:7)
undefined
与not defined
的错误不同。 undefined
是声明的变量的值,当not defined
的错误表示您的变量未声明时。
undefined
的示例:
let elemContent = document.getElementById('content');
let a = null;
let b = 2;
let whatever;
console.log(whatever)
elemContent.innerHTML += a || 'ok'; // "ok"
elemContent.innerHTML += b || 'ok'; // "2"
elemContent.innerHTML += whatever || 'ok'; // "whatever is undefined"

<div id="content"></div>
&#13;
not defined
错误的示例:
let elemContent = document.getElementById('content');
let a = null;
let b = 2;
elemContent.innerHTML += a || 'ok'; // "ok"
elemContent.innerHTML += b || 'ok'; // "2"
elemContent.innerHTML += whatever || 'ok'; // "ERROR: whatever is not defined"
&#13;
<div id="content"></div>
&#13;
这是一个例子,你如何检查,声明变量并且它有一个值(不是undefined
):
let test = "test";
if (typeof test !== undefined) {
console.log("'test' is declared");
if(test) {
console.log("'test' has a value (not 'null', 'false', 'undefined'...)");
}
}
&#13;
答案 3 :(得分:2)
确认undefined是假的:
var whatever = undefined;
console.log(whatever || "undefined is really falsy");
&#13;
答案 4 :(得分:0)
let elemContent = document.getElementById('content');
let a = null;
let b = 2;
let c;
elemContent.innerHTML += a || 'ok'; // "ok"
elemContent.innerHTML += b || 'ok'; // "2"
elemContent.innerHTML += c || 'ko'; // "ko"
elemContent.innerHTML += whatever || 'ok'; // "ERROR: whatever is not defined"
c是undefined
。无论是undeclared