我有一个包含以下地址的javascript对象
var addressList = [
{"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
{"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]
我想为它添加另一个“地址”,所以我有类似下面的内容
[
{"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
{"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"},
{"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]
我无法弄清楚如何做到这一点?
答案 0 :(得分:2)
使用Array#push
向数组添加新对象:
addressList.push({"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"});
答案 1 :(得分:1)
我不清楚你遇到了什么,但你遇到的可能问题是你提供的第一个片段是一个javascript对象,第二个片段是一个数组。你需要这样的东西:
var addressList = [];
addressList.push({"AddressID":"10011",...});
然后,您可以使用forEach迭代列表:
addressList.forEach(function(address) {
alert(address.AddressID);
doSomethingWithAddress(address);
});
您可以在MDN
上阅读有关数组的更多信息答案 2 :(得分:0)
addressList.push({AddressID:1234,Country:'Foo',...});