Javascript检查对象是否为空或空字段和数组

时间:2018-04-18 20:04:37

标签: javascript arrays typescript object

我有一个拥有大量对象和嵌入式数组的数组。我需要遍历整个数组以查看是否有空或空。我的问题是检查数组以及数组是否返回空。我一直在获取对象数组,它们不是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添加到我的计数中。

3 个答案:

答案 0 :(得分:2)

如果您需要检查数组的ExampleDatalength值,可以将 Truthy - Falsy 值视为遵循:

null
  • if (Array.isArray(progressBarCriteria[i]) && progressBarCriteria[i].length) { // This is an array and is not empty. } 检查该值是否为数组。
  • 如果此Array.isArray(progressBarCriteria[i])progressBarCriteria[i].length,则布尔值为0,则为false

答案 1 :(得分:0)

您可以使用递归函数来执行此操作。重要的是要注意javascript数组中的对象。因此,您需要按if (typeof arr === 'object' && !(arr instanceof Array))检查对象。有关更多信息,请检查thisthis

&#13;
&#13;
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])
    
    }
  
  }   

}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我能够看到这两个答案并提出了这个有效的解决方案。这是使用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
    }
  }
}