javascript - 如何使用类访问数组中的某个索引?

标签 javascript html

我只想访问价格指数并为每个服务员添加它们。

我应该为此使用二维数组吗?

我无法只选择价格指数。

例如当我记录这个时

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/

相关文章:

javascript - 父窗口中的新 JSP 关闭弹出子 JSP 页面

javascript - 我需要使用 javascript 在 html 表单中创建一个图像元素及其所有属性,我该怎么做?

javascript - 使用 ng-template 进行 ng-select 时,清除图标 'x' 丢失

java - 从 java 服务器页面中删除所有 HTML

javascript - 如何在 Angular JS 中添加属性和从元素中删除属性

javascript - 是否可以在本地运行 vue 生产构建?

javascript - Firefox 版本 : chrome. tabs.onUpdated.addListener

javascript - 加载新的 html 页面时无法使用 javascript 变量

php - 在 html 中显示数据库中的特定值

javascript - 使用 React 函数组件创建空数组变量