我只想访问价格指数并为每个服务员添加它们。
我应该为此使用二维数组吗?
我无法只选择价格指数。
例如当我记录这个时
console.log(waiters[0].order.price);
结果是:未定义。
//Waiter Constructor
class Waiter{
constructor (name, order, total){
this.name = name;
this.order = [];
this.total = total;
}
}
//Array to store waiters
const waiters = [
new Waiter('Timo'),
new Waiter('Lucian')
];
//
//Food object
//
class Item {
constructor (item, price) {
this.item = item;
this.price = price;
}
}
//Main food array
const mainFood = [
new Item ('Peene Primvera', 14.50),
new Item("Lasagne", 14.50)
];
//Form which is submitted to add the the food and price to the order array
formEl.onsubmit = function (e){
const foodItem = foodMain.options[foodMain.selectedIndex].value;
const waiterName = waitersEl.options[waitersEl.selectedIndex].value;
const waiter = waiters.find(({ name }) => name === waiterName);
//New const to do the addition of the price total for the waiter
const total = waiters[0].order.map(priceTotal =>
priceTotal.price).reduce((a, b) => a + b, 0);
if (waiter && foodItem) {
waiter.order.push(foodItem);
waiter.total.add(total);// Trying to add the total price to the
total constructor varriable
console.log(waiters);
};
return false; // prevents redirect/refresh
};
例如:
0: Waiter
name: "Timo"
order: (2) ["Peene Primvera (14.5)", "Peene Primvera (14.5)"]
total: undefined
我只想在这里选择每个项目的价格并进行计算。
结果将是总计 = 29。
最佳答案
您可以使用 Array.map()
的组合和 Array.reduce()
waiters[0]
.order //As order is an array, so you need to iterate
.map(o => o.price) //Will get an array of price i.e. [14.5, 14.5]
.reduce((a, b) => a + b, 0); //Iterate array and adding current value with previous value, starting with default value 0
class Waiter {
constructor(name) {
this.name = name;
this.order = [];
this.total = 0;
}
addFood = function(item) {
this.order.push(item);
this.total = this.order.map(o => o.price).reduce((a, b) => a + b, 0)
}
}
class Item {
constructor(item, price) {
this.item = item;
this.price = price;
}
}
const waiters = [
new Waiter('Timo')
];
var waiter = waiters[0];
waiter.addFood(new Item('Peene Primvera', 14.50));
console.log(waiter.total)
waiter.addFood(new Item('Lasagne', 14.50));
console.log(waiter.total)
关于javascript - 如何使用类访问数组中的某个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429338/