html页面中数组的输出
我试图将数组中的数组内容输出到HTML页面上的一个小区域。我只能输出一维数组 简单地说,预期的数组有许多属性,但我很难找到正确的代码来输出嵌套在数组中的数组 属性是; 整合器 位置字符串 邮政编码字符串 其他属性可能会添加到该行中 为了输出信息,我使用了以下代码,我只能在单个数组上使用这些代码,即使我改为使用[I][x] document.writeID+i+为: document.write+LocationArray[i]+ 如何正确创建一个能够存储信息的数组,然后输出其中的特定部分?eg显示LocationArray[2][3]的内容html页面中数组的输出,html,arrays,multidimensional-array,Html,Arrays,Multidimensional Array,我试图将数组中的数组内容输出到HTML页面上的一个小区域。我只能输出一维数组 简单地说,预期的数组有许多属性,但我很难找到正确的代码来输出嵌套在数组中的数组 属性是; 整合器 位置字符串 邮政编码字符串 其他属性可能会添加到该行中 为了输出信息,我使用了以下代码,我只能在单个数组上使用这些代码,即使我改为使用[I][x] document.writeID+i+为: document.write+LocationArray[i]+ 如何正确创建一个能够存储信息的数组,然后输出其中的特定部分?eg显
写document.write是一种有效的方法,还是有更好的方法?我整理了一些东西,可以帮助您。在最后回答您关于“以正确的方式”创建数组的问题;有两种可能性: 使用基于“属性”的属性创建数组:var locationsArray=[{ID:123,位置:'blablabla',Postalcode:'1234'}]; 使用字符串键创建数组:var locationsArray=[{'ID':123,'Location':'blabla','Postalcode':'1234'}]; 在我的例子中,我使用了第一次尝试 关于你的第二个问题:document.write只在文档末尾写。如果您想写入网站的特定区域,例如,创建一个容器并给它一个id。然后更改所创建容器的innerHTML属性,就像我在示例中所做的那样 HTML:
<div id="locations"></div>
<button onclick="printLocations()">Print Locations</button>
function printLocations() {
var locationsArray = [{
ID : 123,
Location : 'Candyland',
Postalcode : '1234'
}, {
ID : 456,
Location : 'Middle-Earth',
Postalcode : '4567'
}
];
var locationsHtml = '';
for (var index in locationsArray) {
locationsHtml += 'ID: ' + locationsArray[index].ID + ', ' +
'Location: ' + locationsArray[index].Location + ', ' +
'Postalcode: ' + locationsArray[index].Postalcode + '<br />';
}
console.log(locationsHtml);
document.getElementById('locations').innerHTML = locationsHtml;
}
var locationsHtml = locationsArray[1].ID + locationsArray[1].Location + etc...;
/*with string-keys: var locationsHtml = locationsArray[1]['ID'] + etc...;*/
document.getElementById('locations').innerHTML = locationsHtml;