Why For-in循环返回'arg'当循环为空时

Why For- in loop returns 'arg' when loop is empty

本文关键字:循环 arg Why For-in 返回      更新时间:2024-05-18

我正在对JSON对象进行迭代

我的JSON结构类似于

{"someinfo":{"Parameter":}"ABC":"123","xyz":"456"}}

 for (var tempVal in jsonObj.someinfo.Parameter) {
//print tempval
}

当填充JSON中的"Parameter"时,上面的循环将返回正确的值。

如果为空,则会打印arg

JSON中的空"参数"看起来像:

{"someinfo":{"Parameter":"}}

为了在空或非空时打印正确的值,是否有任何方法可以用于循环

填充的Parameterobject空的Parameterstring

var jsonObj1={"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}};
var jsonObj2={"someinfo":{"Parameter":""}};
alert("Full: "+typeof jsonObj1.someinfo.Parameter+" ---- Empty: "+typeof jsonObj2.someinfo.Parameter)

你不能"在字符串中循环",所以如果你改变你的JSON或者像这个一样测试它

if (typeof jsonObj1.someinfo.Parameter==="object") {
  for (var tempVal in jsonObj.someinfo.Parameter) {
  //print tempval
  }
 } else {
  //empty
}

您可以检查jsonObj.someinfo.Parameter是否是这样的对象:

var json = {"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}};
if(typeof json.someinfo.Parameter === "object") {
  for(var key in json.someinfo.Parameter) {
    // print key
  }
} else {
  // Do something when it is not an object (empty)
}