2

我正在使用 JavaScript JSON 对象。我不确定这是编写 JSON 对象的正确方法:-

var address={
    details:{
        "martin":[{"full_name":"James Martin"},{"address":"Florida"},{"phone":"897657834"}],
        "luthar":[{"full_name":"Luther king"},{"address":"Boston"},{"phone":"9856568789"}],
        "jonson":[{"full_name":"Jonson vierra"},{"address":"New york"},{"phone":"98654567887"}]
    }
}

现在,我想在表格中显示每个人的每个元素。我可以通过编写手动执行此操作:

<table border=1>
<tr>
<td><script>document.write(address.details.martin[0].full_name)</script></td>
<td><script>document.write(address.details.martin[1].address)</script></td>
<td><script>document.write(address.details.martin[2].phone)</script></td>
</tr>
</table>

对所有 3 个人都这样,但我想通过使用循环来获取每个人的全部细节。我怎样才能通过使用循环轻松做到这一点?

4

2 回答 2

2

我会按照这些思路做一些事情:

for (var i in address.details)
{
    document.write('<tr><td>' + address.details[i][0]['full_name'] + '</td><td>' + address.details[i][1]['address'] + '</td><td>' + address.details[i][2]['phone'] + '</td></tr>');
}

要跟进此代码,应输出包含所需数据的表格:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>An XHTML 1.0 Strict standard template</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>

<body>
    <script>
    var address={
        details:{
        "martin":[{"full_name":"James Martin"},{"address":"Florida"},{"phone":"897657834"}],
        "luthar":[{"full_name":"Luther king"},{"address":"Boston"},{"phone":"9856568789"}],
        "jonson":[{"full_name":"Jonson vierra"},{"address":"New york"},{"phone":"98654567887"}]
        }
    }
    </script>
    <table border=1>
    <script>
        for (var i in address.details)
        {
            document.write('<tr><td>' + address.details[i][0]['full_name'] + '</td><td>' + address.details[i][1]['address'] + '</td><td>' + address.details[i][2]['phone'] + '</td></tr>');
        }
    </script>
    </table>
</body>

于 2013-04-09T14:15:23.830 回答
1
for (var personName in address.details) {
  if (address.details.hasOwnProperty(personName)) {
    address.details[personName]
    //  [{"full_name":"James Martin"},{"address":"Florida"},{"phone":"897657834"}]
    // you could now loop through the personName's array
  }
}

您完全可以控制数据结构吗?好像有点绕?

于 2013-04-09T14:14:54.207 回答