【发布时间】: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