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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43309712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:49:45  来源:igfitidea点击:

How to check if a value is not null and not empty string in JS

javascript

提问by mistery_girl

Is there any check if a value is not null and not empty string in Javascript? I'm using the following one:

是否有任何检查值是否在 Javascript 中不为空且不为空字符串?我正在使用以下一个:

var data; //get its value from db 
if(data != null && data != '') {
   // do something
}

But I'm wondering if there is another better solution. Thanks.

但我想知道是否有其他更好的解决方案。谢谢。

回答by Gershon Papi

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
}

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

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

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, undefinedand empty strings, would not.

这两部分代码之间的区别在于,对于第一部分,每个不是专门为 null 或空字符串的值都将输入if. 但是,在第二个,每一个真正的十岁上下的价值将进入iffalse0nullundefined和空字符串,不会。

回答by Anna Fohlmeister

Both nulland an empty string are falsy values in JS. Therefore,

这两个null和一个空字符串是JS falsy值。所以,

if (data) { ... }

is completely sufficient.

是完全足够的。

A note on the side though: I would avoid having a variable in my code that could manifest in different types. If the data will eventually be a string, then I would initially define my variable with an empty string, so you can do this:

不过,请注意:我会避免在我的代码中包含一个可能以不同类型显示的变量。如果数据最终将是一个字符串,那么我最初会用一个空字符串定义我的变量,所以你可以这样做:

if (data !== '') { ... }

without the null (or any weird stuff like data = "0") getting in the way.

没有 null(或任何奇怪的东西,如data = "0")妨碍。

回答by vipinlalrv

Instead of using

而不是使用

if(data !== null && data !== ''  && data!==undefined) {

// do something
}

You can use below simple code

您可以使用下面的简单代码

if(Boolean(value)){ 
// do something 
}
  • Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false
  • Other values become true
  • 直觉上为“空”的值,例如 0、空字符串、null、undefined 和 NaN,将变为 false
  • 其他值变为真

回答by pilot

I often test for truthy value and also for empty spaces in the string:

我经常测试真值以及字符串中的空格:

if(!(!data || data.trim().length === 0)) {
  // do something here
}

If you have a string consisting of one or more empty spaces it will evaluate to true.

如果您有一个由一个或多个空格组成的字符串,它将评估为真。

回答by Sam Hasler

if (data?.trim().length > 0) {
   //use data
}

the ?.optional chaining operatorwill short-circuit and return undefinedif data is nullish(nullor undefined) which will evaluate to false in the ifexpression.

所述?.可选的链接操作者将短路和返回undefined如果数据是nullishnullundefined),其将计算为在虚假if表达。

回答by Bhagawat

Both null and empty could be validated as follows:

null 和 empty 都可以验证如下:

<script>
function getName(){
    var myname = document.getElementById("Name").value;
    if(myname != '' && myname != null){
        alert("My name is "+myname);
    }else{
        alert("Please Enter Your Name");
    }       
}

回答by beletebelay

try it----------

试试吧----------

function myFun(){
var inputVal=document.getElementById("inputId").value;
if(inputVal){
document.getElementById("result").innerHTML="<span style='color:green'>The value is "+inputVal+'</span>';
}
else{
document.getElementById("result").innerHTML="<span style='color:red'>Something error happen! the input May be empty.</span>";
}
}
<input type="text" id="inputId">
<input type="button" onclick="myFun()" value="View Result">
<h1 id="result"></h1>

回答by oriberu

I got so fed up with checking for null and empty strings specifically, that I now usually just write and call a small function to do it for me.

我已经厌倦了专门检查空字符串和空字符串,以至于我现在通常只是编写和调用一个小函数来为我做这件事。

/**
 * Test if the given value equals null or the empty string.
 * 
 * @param {string} value
**/
const isEmpty = (value) => value === null || value === '';

// Test:
isEmpty('');        // true
isEmpty(null);      // true
isEmpty(1);         // false
isEmpty(0);         // false
isEmpty(undefined); // false