JavaScript中的双管道(||)抛出错误而不是评估为假

时间:2017-09-26 10:32:55

标签: javascript undefined boolean-operations

我读到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"

http://jsfiddle.net/ueqo6yko

undefined是否是JavaScript中的假值,或者如何理解这一矛盾?

5 个答案:

答案 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)

undefinednot 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;
&#13;
&#13;

not defined错误的示例:

&#13;
&#13;
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;
&#13;
&#13;

这是一个例子,你如何检查,声明变量并且它有一个值(不是undefined):

&#13;
&#13;
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;
&#13;
&#13;

答案 3 :(得分:2)

确认undefined是假的:

&#13;
&#13;
var whatever = undefined;
console.log(whatever || "undefined is really falsy");
&#13;
&#13;
&#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