检查 JavaScript 中的变量是否为空?

Checking whether variable is empty in JavaScript?

有两种JavaScript代码用于调查empty/full变量:

if(variable == ''){}

if(!variable){}

我测试了他们两个,我得到了相同的结果。现在我想知道,(首先)它们是等价的吗?以及(第二)哪个更标准地检查 empty/full 变量?

var variable1 = 'string';
var variable2 = 12;
var variable3 = true;


if(variable1 == ''){alert('empty-one');}
if(variable2 == ''){alert('empty-one');}
if(variable3 == ''){alert('empty-one');}

if(!variable1){alert('empty-two');}
if(!variable2){alert('empty-two');}
if(!variable3){alert('empty-two');}

如您所见,没有alert

在 javascript null,'',0,NaN,undefined 考虑 falsey 在 javascript.

从某种意义上说,你可以双向检查空

但是你的第一个代码正在检查它 ''

你的第二个条件是检查你的值是其中之一 (null,'',0,NaN,undefined)

在我看来你的第二个条件比第一个好,因为我不必单独检查 null,'',0,NaN,undefined

First 不是标准的,它只适用于定义的空字符串。

如果值不真实(意味着有意义的东西),其他方法也有效

例如 var a;

a == '' will give false result
! a     will produce true

例如var a = null;

a == '', // false
! a      // true

var a = false;

a == '' // fase
! a     // true

var a = NaN

a == ''  // false
! NaN     // true

true == 'true' // false, Boolean true is first converted to number and then compared

0 == '' // true, string is first converted to integer and then compared

==使用The Abstract Equality Comparison Algorithm比较两个操作数

更多详情请访问http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

不,它们不等价。如果首先检查 variable 的值是否等于空字符串 ('')。因此,如果 variable 的值为 '',则 case first 为真。但是第二种情况对于所有错误的值都是正确的,即 false, 0, '', null, undefined