在 JS 中如何检查一个值是否为空或者不是空字符串

在 Javascript 中有没有检查一个值是否为 null 或者不是空字符串?我用的是下面这个:

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

但我想知道还有没有更好的解决办法,谢谢。

484133 次浏览

如果您真的想确认一个变量不是 null,而且不是一个空字符串,那么您应该写:

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

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

然而,如果您只是想确保代码只为“合理的”值运行,那么您可以像其他人已经说过的那样,编写:

if (data) {
// do something
}

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

这两部分代码的不同之处在于,对于第一部分代码,每个非特定为 null 或空字符串的值都将输入 if。但是,在第二种情况下,每个 true-ish 值将输入 if: false0nullundefined和空字符串,而不会输入。

在 JS 中,null和空字符串都是假值,

if (data) { ... }

已经足够了。

不过另外要注意的是: 我会避免在代码中出现可以在不同类型中显示的变量。如果数据最终是一个字符串,那么我将首先用一个空字符串定义我的变量,所以您可以这样做:

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

没有空(或任何奇怪的东西,如 data = "0")得到的方式。

Null 和 null 都可以验证如下:

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

试试看

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>

而不是利用

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


// do something
}

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

if(Boolean(value)){
// do something
}
  • Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false
  • 其他价值观成为现实

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

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

如果您有一个由一个或多个空格组成的字符串,它的计算结果将为 true。

我特别厌倦了检查空字符串和空字符串,现在我通常只是编写和调用一个小函数来完成这项工作。

/**
* 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
if (data?.trim().length > 0) {
//use data
}

如果数据是 nullish(nullundefined) ,那么 ?. 可选链接操作符将短路并返回 undefined,这将使 if表达计算为假。

当我们编码本质上是空的时候,可能意味着下列任何一种情况;

  • 0表示数值
  • 0.0作为浮点值
  • “0”与字符串值相同
  • ’0.0’表示字符串值
  • Null 与 Null 值一样,因为它也可能捕获未定义的值,也可能捕获未定义的值
  • 未定义的价值
  • 如果我们想要捕获假值,那么每次机会0也是真值
  • ”没有空格或制表符的空 sting 值
  • 字符串只有空格或制表符

In real life situation as OP stated we may wish to test them all or at times we may only wish to test for limited set of conditions.

一般来说,if(!a){return true;}在大多数情况下都能发挥作用,但它不会涵盖更广泛的一系列条件。

另一个成功的黑客攻击是 return (!value || value == undefined || value == "" || value.length == 0);

但如果我们需要控制整个过程呢?

在本地核心 JavaScript 中没有简单的“鞭打”解决方案,它必须被采用。考虑到我们放弃了对遗留 IE11的支持(老实说,即使是 Windows 也应该这样做) ,在所有现代浏览器的解决方案出生的挫折工程;

 function empty (a,b=[])
{if(!Array.isArray(b)) return;
var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
{return true;};
return false;};`

解决方案背后的逻辑是函数有两个参数 B,a 是我们需要检查的值,b 是一个设置条件的数组,我们需要从上面列出的预定义条件中排除。B 的默认值设置为空数组[]。

First run of function is to check if b is an array or not, if not then early exit the function.

下一步是计算数组差从 [null,'0','0.0',false,undefined,'']和数组 b 如果 b 是一个空数组预定义的条件将立场,否则它将删除匹配值。

條 = [预定义集]-[要排除的集] Filter 函数正是利用了它。 现在我们已经在数组中设置了条件,所有我们需要做的就是检查 value 是否在条件数组中。 Include 函数完全不需要编写自己的恶心循环,让 JS 引擎来完成繁重的工作。

抓到你了 如果我们要将一个字符串转换为字符串进行比较,那么0和0.0可以正常运行,但是 Null 和 UnDefinition 可以通过错误阻塞整个脚本来运行。我们需要边界情况的解决方案。下面简单的 ||覆盖边缘情况下,如果第一个条件不满足。通过 include 运行另一个早期检查,如果没有满足要求,将提前退出。

if(conditions.includes(a)||  (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))

饰()功能将涵盖更广泛的空白和制表符只值,将只在边缘情况下发挥作用的情况。

Play ground

function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}


console.log('1 '+empty());
console.log('2 '+empty(''));
console.log('3 '+empty('      '));
console.log('4 '+empty(0));
console.log('5 '+empty('0'));
console.log('6 '+empty(0.0));
console.log('7 '+empty('0.0'));
console.log('8 '+empty(false));
console.log('9 '+empty(null));
console.log('10 '+empty(null,[null]));
console.log('11 dont check 0 as number '+empty(0,['0']));
console.log('12 dont check 0 as string '+empty('0',['0']));
console.log('13 as number for false as value'+empty(false,[false]));

让我们把它复杂化——如果我们要比较的值是数组本身,并且可以尽可能地深度嵌套,那会怎样。如果我们要检查数组中的任何值是否为空,那么它可以是一个边缘业务案例。

function empty (a,b=[]){
if(!Array.isArray(b)) return;


conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(Array.isArray(a) && a.length > 0){
for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;}
}
    

if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}


console.log('checking for all values '+empty([1,[0]]));
console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));

我在框架中采用的简单而广泛的用例功能;

  • 控制在给定的情况下空的确切定义
  • 赋予控制权以重新定义空的条件
  • 可以比较字符串、数字、浮点数、真值、空值、未定义和深度数组中的几乎所有内容
  • 考虑到可恢复性和灵活性,制定了解决方案。如果要处理一两个简单的情况,所有其他的答案都是适合的。然而,在编写上述代码片段时,定义空更改总是会使工作在这种情况下完美无缺。

function validateAttrs(arg1, arg2, arg3,arg4){
var args = Object.values(arguments);
return (args.filter(x=> x===null || !x)).length<=0
}
console.log(validateAttrs('1',2, 3, 4));
console.log(validateAttrs('1',2, 3, null));
console.log(validateAttrs('1',undefined, 3, 4));
console.log(validateAttrs('1',2, '', 4));
console.log(validateAttrs('1',2, 3, null));

检查字符串是 undefinednull还是 ""的简单解决方案:-

const value = null;
if(!value) {
console.log('value is either null, undefined or empty string');
}