簡體   English   中英

JavaScript檢查對象是否為空或空字段和數組

[英]Javascript Check Object for empty or null fields and arrays

我有一個包含很多對象和嵌入式數組的數組。 我需要遍歷整個數組以查看是否為空或null。 我的問題是檢查數組以及數組是否返回空。 我一直在獲取對象數組,它們不是null或未定義,所以即使長度為0也要添加它們。到目前為止,我得到了什么。

var progressCount = 0;
var progressKeyLength = progressBarCriteria.length;
for (var i = 0; i<progressKeyLength; i++){
  //I can find the arrays here but still not able to check length since they are actually object arrays.
  if(Array.isArray(progressBarCriteria[i])){
    console.log('array' + i);
  }
  if (progressBarCriteria[i] !== null && progressBarCriteria[i] !== ""){
    ++progressCount
  }
}


progressBarCritiria = [
   example1: "",
   example2: "asdasdas",
   example3: 233,
   example4: {asda: 1},
   example5: {asadasda: "asdasdA"},
   example6: "",
   example7: [],
   example8: [1, 12312],
   example9: [{1: "ad"}, {1: 12312}],
]

因此,不應將1、6和7添加到我的計數中。

如果需要檢查數組的lengthnull值,則可以考慮Truthy - Falsy值,如下所示:

if (Array.isArray(progressBarCriteria[i]) && progressBarCriteria[i].length) {
   // This is an array and is not empty.
}
  • Array.isArray(progressBarCriteria[i])檢查該值是否為數組。
  • 如果該progressBarCriteria[i].length0則布爾值將為false ,否則為true

您可以使用遞歸函數來做到這一點。 重要的是要注意,在javascript數組中是對象。 因此,您需要通過if (typeof arr === 'object' && !(arr instanceof Array))檢查對象。 有關更多信息,請檢查thisthis

 function recursive_array_chekc (arr) { //check if arr is an object if (typeof arr === 'object' && !(arr instanceof Array)) { //check if object empty if (Object.keys (arr).length === 0) { //do something if empty console.log ('this object is empty'); } else { //check object properties recursivly for (var key in arr) if (arr.hasOwnProperty (key)) recursive_array_chekc (arr[key]) } } else if (Array.isArray (arr)) { //check if array is empty if (arr.length === 0) { //do something if empty console.log ('this array is empty'); } else { //check array elements recursivly for (var i = 0; i < arr.length; i++) recursive_array_chekc (arr[i]) } } } 

我能夠看到兩個答案,並提出了這個可行的解決方案。 這是使用Typescript的代碼,很抱歉造成混淆。

for (var i = 0; i<progressKeyLength; i++){
  if (!(progressBarCriteria[i] instanceof Array)){
    if(progressBarCriteria[i] !== null && progressBarCriteria[i] !== "") {
        ++progressCount
    }
  } else {
    let current = progressBarCriteria[i];
    if (Array.isArray(current) && current.length !== 0){
      ++progressCount
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM