且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JS中检查值是否为空且不是空字符串

更新时间:2023-01-05 22:22:44

如果你真的想确认一个变量不是null而不是一个特殊的空字符串,你会写:

If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:

if(data !== null && data !== '') {
   // do something
}

请注意,我更改了代码以检查类型是否相等(!== | === )。

Notice that I changed your code to check for type equality (!==|===).

但是你只是想确保一个代码只运行合理的值,然后你可以像其他人已经说过的那样写:

If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:

if (data) {
  // do something
}

因为在javascript中,空值和空字符串都等于false(即 null == false )。

Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).

这两部分代码之间的区别在于,对于第一部分代码,每个非特定空值或空字符串的值都将输入 if 。但是,在第二个,每个true-ish值将进入如果 false 0 null undefined 和空字符串,不会。

The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.