前端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("數組不為空")
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM