1

我正在遍历 JSON 文件的设置键。有时这些键的值会是空的(null?是 null 正确的词吗?)。因此,它会在以后的交互中产生错误。我想将这些空值从发送到val[].

示例 JSON:

post_a: "THis is key 1"
post_b: "this is key 2"
post_c: "this is key 3"
post_d: "" 
 // I want to filiter out post_d because it is empty

环形:

 keys = ["post_a", "post_b", "post_c", "post_d"]; 
 val = [];
 $.each(keys, function(i, key) {
     val[i] = data[key];
     return val[i];
  });

目前,在此循环完成后:val.length = 4 如果按预期工作:val.length = 3

4

2 回答 2

1
keys = ["post_a", "post_b", "post_c", "post_d"]; 
 val = [];
 $.each(keys, function(i, key) {
     if(data[key]){
       val[i] = data[key];
       return val[i];
     }
  });

您的代码中没有空检查。它只是一直添加所有内容。试试上面的

于 2013-07-21T04:35:07.453 回答
1
if (data[key]) {
    // var is defined, do your code
}
于 2013-07-21T04:36:05.283 回答