【问题标题】:First result undefined when looping through JSON string循环遍历 JSON 字符串时的第一个结果未定义
【发布时间】:2021-10-01 08:42:09
【问题描述】:
const obj = {
  "accountId": "number",
  "prefix": "string",
  "firstName": "string",
  "middleName": "string", 
  "lastName": "string",
  "suffix": "", 
  "dateOfBirth": "string",
  "email": "string",
  "phone": "string", 
  "status": ""
};
//JSON.stringify(obj); //assuming this does nothing since it's already a JSON string?
//JSON.parse(obj); // This kills the process.
const required = function(k) {
    v = obj[key];
    if (v == ''){
        checked = "<br>A required component " + k + " was missing from this message.";
        return checked;
    } else {
        checked = "<br>the value of " + k + " is " + v;
        return checked;
    }
    
}
for (var key of Object.keys(obj)) {
    document.getElementById("demo").innerHTML = document.write(required(key));
};

我在 w3 tryit(js) 编辑器中运行上述内容。返回如下

undefined


the value of accountId is number
the value of prefix is string
the value of firstName is string
the value of middleName is string
the value of lastName is string
A required component suffix was missing from this message.
the value of dateOfBirth is string
the value of email is string
the value of phone is string
A required component status was missing from this message.

我试图理解为什么第一行输出显示为未定义。在我的用例中,这会给工作带来麻烦。查看我尝试过的各种答案 forEach 并得到相同的结果。尝试抛出似乎死了的 JSON.parse(obj) 。我还添加了 JSON.stringify(obj),它不会改变输出。

我已经梳理了好几次,我很确定我没有错过像 , 或 ; 这样愚蠢的东西。

在第一行作为未定义返回之后,一切都按预期返回。 我被卡住了。

【问题讨论】:

  • document.write 总是 返回undefined。请改用document.getElementById("demo").innerHTML += required(key);
  • 这里是另一件事你正在使用key 来获取对象值,它应该是k。 v = obj[k] 而不是。 v = obj[key] jsfiddle.net/6ucjpbdm/1 检查上面的小提琴。

标签: javascript json loops object key


【解决方案1】:

看起来像从循环中删除 document.getElementById("demo").innerHTML = 在 tryit 编辑器中起到了作用。

for (var key in obj) {
    document.write(required(key));
};

导致

the value of accountId is number
the value of prefix is string
the value of firstName is string
the value of middleName is string
the value of lastName is string
A required component suffix was missing from this message.
the value of dateOfBirth is string
the value of email is string
the value of phone is string
A required component status was missing from this message.

我有点明白为什么......

【讨论】:

    【解决方案2】:

    document.write 总是 返回值undefined。因此,在每次循环迭代中,您实际上将“演示”元素的 innerHTML 设置为“未定义”。对document.write 的调用将实际输出附加到body 元素。您应该能够在开发工具的元素选项卡中看到它。

    【讨论】:

      猜你喜欢
      • 2015-11-25
      • 1970-01-01
      • 2013-02-19
      • 2016-01-31
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多