for (var i = 1; i < address.length; i++) {
var markers = [{"name":"marker"+i, "address":address[0]}];
}
循环后我希望我的json标记看起来像
name: marker1, address: aaaa
name: marker2, address: abcd
name: marker3, address: adf
帮我修复我的代码。在此先感谢,我是json的新手,我不知道如何用空值初始化它并在for循环中插入值。
答案 0 :(得分:1)
好的,所以这很容易。
var markers = [];
// This still needs address to be an array, also still don't understand why you don't begin at the start of the array
for (var i = 1; i < address.length; i++) {
markers.push({
name: "marker" + i,
address: address[i]
});
}
// If you do want to start at the begininning of the array, but still want it to start with "markers1"
for (var i = 0; i < address.length; i++) {
markers.push({
name: "marker" + (i + 1),
address: address[i]
});
}
假设地址已经是一个有效的javascript数组,这将为您提供一个如下所示的数组:
[
{ name: "marker1", address: "whatever was here" },
{ name: "marker2", address: "whatever was there" }
]
上次修改:已删除的内容与新编辑的问题无关。
答案 1 :(得分:0)
var address = ['aaaa', 'abcd', 'adf'];
var markers = [];
for (var i = 0; i < address.length; i++) {
markers.push({
name: "marker" + (+i + 1),
address: address[i]
});
}
var jsonMarkers = JSON.stringify(markers);
// And jsonMarkers will look like :
//"[{"name":"marker1","address":"aaaa"},{"name":"marker2","address":"abcd"},{"name":"marker3","address":"adf"}]"