如何在JS中检查值是否为空且不是空字符串 [英] How to check if a value is not null and not empty string in JS
问题描述
在Javascript中是否检查值是否为空且不是空字符串?我正在使用以下一个:
Is there any check if a value is not null and not empty string in Javascript? I'm using the following one:
var data; //get its value from db
if(data != null && data != '') {
// do something
}
但我想知道是否还有其他更好的解决方案。谢谢。
But I'm wondering if there is another better solution. Thanks.
推荐答案
如果你真的想确认一个变量不是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.
这篇关于如何在JS中检查值是否为空且不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!