简体   繁体   English

如何循环并正确打印

[英]How to loop through and print out correctly

I Know why I'm getting undefined but i have no idea how to solve.我知道为什么我变得未定义,但我不知道如何解决。

Tried to put null, but it is taking in as a text试图将 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>";
    }

Hi, for Isabella there is no email, hence I'm getting undefined when I loop through to print out their details on html, however what I'm expecting is for the email portion to be empty in the table for Isabella.嗨,对于伊莎贝拉来说,没有电子邮件,因此当我循环打印他们在 html 上的详细信息时,我变得未定义,但是我期望伊莎贝拉的表格中的电子邮件部分为空。 Is there a way to solve it?有办法解决吗?

You can use logical OR ( || in JavaScript), which will use the second value (empty string in this case) if the first value (email) is undefined :您可以使用逻辑 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM