我知道为什么我变得不确定,但是我不知道如何解决。
试图放入null,但它以文本形式出现
var text ='{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony@json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda@json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick@json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for(var i in obj.employees)
{
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>"
+ "<td>" + obj.employees[i].email + "</td></tr>";
}
您好,对于Isabella来说,没有电子邮件,因此,当我遍历以在html上打印其详细信息时,我变得不确定,但是我期望Isabella表中的电子邮件部分为空。有办法解决吗?
答案 0 :(得分:0)
您可以使用逻辑OR(JavaScript中的||
),如果第一个值(电子邮件)为undefined
,它将使用第二个值(在这种情况下为空字符串):
var text = '{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony@json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda@json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick@json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for (var i in obj.employees) {
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>" +
"<td>" + (obj.employees[i].email || '') + "</td></tr>";
}
<table id="table"></table>