嵌套数组是指数组中的元素也是数组。在这种结构中,可以通过多级索引来访问特定的元素。例如,一个包含多个订单的数组,每个订单又是一个包含商品信息的数组,每个商品信息包括价格和数量。
嵌套数组可以是任意深度的,常见的类型包括:
假设我们有一个嵌套数组,表示多个订单,每个订单包含多个商品,每个商品有价格和数量。我们需要计算所有商品的总价。
const orders = [
[
{ price: 10, quantity: 2 },
{ price: 5, quantity: 3 }
],
[
{ price: 20, quantity: 1 },
{ price: 15, quantity: 4 }
]
];
function calculateTotalPrice(orders) {
let totalPrice = 0;
for (const order of orders) {
for (const item of order) {
totalPrice += item.price * item.quantity;
}
}
return totalPrice;
}
console.log(calculateTotalPrice(orders)); // 输出: 115
原因:可能是某些订单或商品信息缺失价格或数量字段,或者数据类型不正确(例如,价格或数量是字符串而不是数字)。
解决方法:
function calculateTotalPrice(orders) {
let totalPrice = 0;
for (const order of orders) {
for (const item of order) {
const price = typeof item.price === 'number' ? item.price : 0;
const quantity = typeof item.quantity === 'number' ? item.quantity : 1;
totalPrice += price * quantity;
}
}
return totalPrice;
}
通过这种方式,可以确保即使在数据格式不一致的情况下,计算结果仍然是准确的。
领取专属 10元无门槛券
手把手带您无忧上云