![](/img/trans.png)
[英]Adding a javascript function to an already existing javascript object
[英]adding objects to an already existing javascript object
我有一个包含以下地址的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"}
]
我不知道该怎么做?
使用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"});
我不清楚您遇到了什么,但是您遇到的可能问题是您提供的第一个代码段是一个javascript对象,第二个代码段是一个数组。 您需要这样的事情:
var addressList = [];
addressList.push({"AddressID":"10011",...});
然后,您可以使用forEach遍历列表:
addressList.forEach(function(address) {
alert(address.AddressID);
doSomethingWithAddress(address);
});
您可以在MDN上阅读有关数组的更多信息
addressList.push({AddressID:1234,Country:'Foo',...});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.