尝试从类中检索值时出现NAN错误?

时间:2019-08-09 17:30:20

标签: javascript html

当我尝试从类方法中映射().reduce()时,出现“ NAN”错误。

提交表单后,所有值都会动态更新。

我想为每个单独的Waiter类存储并添加价格值,并将其存储在Waiter总计中。

我不确定问题是否出在提交表单或类方法addFood的函数中。

我尝试了几种方法pasrseInt(),但不确定语法是否正确。

/*

//Waiters Section

*/


//Waiter Constructor
class Waiter{
    constructor (name){
    this.name = name;
    this.order = [];
    this.total = 0;
    }
    
    
    //function to map() the price argument
    //and then reduce() to get the total
    addFood (item){
    this.order.push(item);
    this.total = this.order.map(o => o.price).reduce((a, b) => a + b, 0);
    }

    
};





//Array to store waiters
const waiters = [
    new Waiter('Timo'),
    new Waiter('Lucian'),
    new Waiter('Arpi')
                  
];




const waitersEl = document.getElementById('waiters');

//Adding the waiters to the options menu
waiters.forEach(({name}) => waitersEl.options.add(new Option(name)));





    /*
    
    //Food Section Main
    
    */
    
    //Food Constructor
    class Item {
      constructor (item, price) {
      this.item = item;
      this.price = price;
      this.label = `${item} (${price})`;
      }
    }
    
    
    
    //Main food array
    const mainFood = [
        new Item ('Peene Primvera', 14),
        new Item("Lasagne", 14),
        new Item("Fillet Steak", 20)
    ];
    
    
    
    const foodMain = document.getElementById('menuMain');
    
    //Addin the options for each food and price item inside the dropdown menu
    mainFood.forEach(({label, item }) => foodMain.options.add(new Option(label, label)));
    
    
    
    
    /*
    
    //Fucntion for when the form is submited it adds the  
    
    */
    const formEl = document.getElementById('mainForm');
    
    formEl.onsubmit = function (e){
        
        //Selecting the choosen index from the user food and which waiter orderd //it which waiter 
        const foodItem = foodMain.options[foodMain.selectedIndex].value;  
        
        const waiterName = waitersEl.options[waitersEl.selectedIndex].value;
        const waiter = waiters.find(({ name }) => name === waiterName);
        
        
        //Logic to check when submited if both feilds are true proceed 
        if (waiter && foodItem) {
            
            //Calling the function addFood from the Waiter
            //class to push the selection to the orders array
            //and then reduce it and put the total in the total argument
            waiter.addFood(foodItem);
            console.log(waiters);
        };
        
         
    
    
        return false; // prevents redirect/refresh
        
    };
    
    <form id="mainForm" action="#">
      <select id="menuMain" name="foodOrder">
      </select>
      <select id="waiters" name="waiterSelection">
      </select>
      <input type="submit" value="Submit">
    </form>

这是我在提交通知总数后得到的:NAN:

0: Waiter
addFood: ƒ (item)
name: "Timo"
order: ["Peene Primvera (14.5)", "Peene Primvera (14.5)"]
total: NaN

我想要的结果是:

0: Waiter
addFood: ƒ (item)
name: "Timo"
order: ["Peene Primvera (14.5)", "Peene Primvera (14.5)"]
total: 29

2 个答案:

答案 0 :(得分:2)

不是将<option>的值设置为Item的标签,而是将其设置为Item数组中的mainFood的索引,而是这样容易获得与所选Item关联的<option>对象。

这里是一个例子:

mainFood.forEach(({label, item }, index) => foodMain.options.add(new Option(label, index)));

然后:

const foodItemIndex = foodMain.options[foodMain.selectedIndex].value; 
const foodItem = mainFood[foodItemIndex];

这是一个有效的版本:

class Waiter {
  constructor(name) {
    this.name = name;
    this.order = [];
    this.total = 0;
  }

  addFood(item) {
    this.order.push(item);
    this.total = this.order.map(o => o.price).reduce((a, b) => a + b, 0);
  }
};

const waiters = [
  new Waiter('Timo'),
  new Waiter('Lucian'),
  new Waiter('Arpi')

];

const waitersEl = document.getElementById('waiters');

waiters.forEach(({
  name
}) => waitersEl.options.add(new Option(name)));

class Item {
  constructor(item, price) {
    this.item = item;
    this.price = price;
    this.label = `${item} (${price})`;
  }
}

const mainFood = [
  new Item('Peene Primvera', 14),
  new Item("Lasagne", 14),
  new Item("Fillet Steak", 20)
];



const foodMain = document.getElementById('menuMain');

mainFood.forEach(({
  label,
  item
}, index) => foodMain.options.add(new Option(label, index)));


const formEl = document.getElementById('mainForm');

formEl.onsubmit = function(e) {

  const foodItemIndex = foodMain.options[foodMain.selectedIndex].value;
  const foodItem = mainFood[foodItemIndex];

  const waiterName = waitersEl.options[waitersEl.selectedIndex].value;
  const waiter = waiters.find(({
    name
  }) => name === waiterName);

  if (waiter && foodItem) {
    waiter.addFood(foodItem);
    console.log(waiters);
  };

  return false; // prevents redirect/refresh
};
<form id="mainForm" action="#">
  <select id="menuMain" name="foodOrder">
  </select>
  <select id="waiters" name="waiterSelection">
  </select>
  <input type="submit" value="Submit">
</form>

答案 1 :(得分:0)

没有更多信息,似乎this.order中的某些数据不是数字。如果值非数字,则ParseInt()将返回NaN

如果此处的数据可能包含非数值数据,则可以使用双波浪号运算符0~~)将索引默认设置为Math.floor(),该运算符将返回{{ 1}},其中0将返回parseInt()

这将修复错误,但是根据您的需要,它可能只是忽略了该问题。如果该数据不打算放在该数组中,我建议调查如何在此设置它。

NaN