前端js判空处理,js字符串判空,js数组判空

1、字符串

js 中,字符串为空会有这么几种形式,""nullundefined,如果在已知变量为空串的情况下可以直接采用 if (string.length == 0) 这种形式,今天总结一下常用的几种方法,方便下次查阅。

1.1、typeof | null | '' 「推荐👉:兼容null、undefined 」
function isEmpty(obj{
  if (typeof obj === 'undefined' || obj == null || obj === '') {
    return true;
  } else {
    return false;
  }
}

该方法是目前使用比较多的,关于 typeof ,js 中提供了 typeof 运算符,用来检测一个变量的类型。

方法使用示例:

if (!isEmpty(value)) {
    alert(value);
}esle{
    alert("数据为空");
}
1.2、trim() 函数
function checkStrIsEmpty(value{
    let str = value.trim();
    if (str.length == 0) {
        console.log('字符串全是空格');
    } else {
        console.log('输入的字符串为:' + value);
    }
}
1.3、正则表达式
var str = '';
if (str.replace(/(^\s*)|(\s*$)/g"").length ==0)
{
    console.log('为空');
}

2、数组

空数组的判断可以说是最常见的了,空数组可以理解为 new Array(),相当于声明了一个新的空数组,程序会自动在堆中为其开辟一块内存空间,需要注意的是它和 var a = [] 生成的内存空间不是同一块,所以不相等。

2.1、arr.length
let arr = [];
if (arr.length == 0){
   console.log("数组为空")
}else {
   console.log("数组不为空")
}
2.2、JSON.stringify(arr) === '[]'
var arr = [];
if(JSON.stringify(arr) === '[]'){
    console.log("数组为空");
}else {
   console.log("数组不为空")
}
2.3、函数方式 「推荐👉:兼容 arr[-1] = '' 」
function isEmptyObject(e{  
    var t;  
    for (t in e)  
        return !1;
    return !0;
}  

使用示例:

if (!isEmptyObject(arr)) {
   console.log("数组为空");
}else {
   console.log("数组不为空")
}
posted @ 2019-12-17 00:09  niceyoo  阅读(14151)  评论(1编辑  收藏  举报