我试图遍历数组,只返回地址和包数,然后将数组中的包总数加起来。问题是,当我在codepen.io中全部编写这些代码时,它告诉我每个name属性都有一个意外的标识符错误。我知道我必须自己处理循环,但是这有什么问题呢?这是我在Codepen.io中看到的内容,如果想要查看Codepen显示的内容,则这里是链接:https://codepen.io/epbutterfield/pen/NBxMQb?editors=0012
我知道它非常简单,但是我必须有一个额外的标识符,或者会丢失一个标识符。...
var deliveryItinerary = [
{
name: Doctor Allen Grant,
address: '123 Jurassic Park Trail, Kualoa Ranch, Hawaii',
zipcode: 96744,
packages: 5
},
{
name: Harry Potter,
address: '4 Privet Drive, Manchester, England',
zipcode: 81726,
packages: 8
},
{
name: Bowen Knight,
address: '1600 Camelot Court, Liverpool, England',
zipcode: 15064,
packages: 2
},
{
name: Van Helsing,
address: '1462 Dracula\'s Castle, Valerious, Transylvania',
zipcode: 18870,
packages: 1
}
];
for (i = 0; i < deliveries.length; i++){
console.log(deliveryItinerary[i].address)
console.log(deliveryItinerary[i].packages){
deliveryItinerary.reduce[i].packages
}
};
答案 0 :(得分:0)
在您的name
值周围添加引号,因为它们是字符串文字而不是JS变量。还可以使用一个额外的变量,称为totalPackages
,以总结循环中的所有程序包。
var deliveryItinerary = [
{
name: 'Doctor Allen Grant',
address: '123 Jurassic Park Trail, Kualoa Ranch, Hawaii',
zipcode: 96744,
packages: 5
},
{
name: 'Harry Potter',
address: '4 Privet Drive, Manchester, England',
zipcode: 81726,
packages: 8
},
{
name: 'Bowen Knight',
address: '1600 Camelot Court, Liverpool, England',
zipcode: 15064,
packages: 2
},
{
name: 'Van Helsing',
address: '1462 Dracula\'s Castle, Valerious, Transylvania',
zipcode: 18870,
packages: 1
}
];
var totalPackages = 0;
for (i = 0; i < deliveryItinerary.length; i++){
console.log(deliveryItinerary[i].address);
console.log(deliveryItinerary[i].packages);
totalPackages += deliveryItinerary[i].packages;
};
console.log(totalPackages);