-1

我有一个 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"}
]

我不知道该怎么做?

4

3 回答 3

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"});
于 2012-09-19T16:48:38.420 回答
1

我不清楚您遇到了什么,但您遇到的可能问题是您提供的第一个片段是一个 javascript 对象,第二个片段是一个数组。你需要这样的东西:

var addressList = [];
addressList.push({"AddressID":"10011",...});

然后,您可以使用 forEach 遍历列表:

addressList.forEach(function(address) {
    alert(address.AddressID);
    doSomethingWithAddress(address);
});

您可以在MDN上阅读有关数组的更多信息

于 2012-09-19T16:55:58.610 回答
0

addressList.push({AddressID: 1234, Country: 'Foo', ...});

于 2012-09-19T16:48:36.047 回答