首页 > 解决方案 > 为什么控制台声称数组未定义?

问题描述

当我运行以下代码变体中的第一个时,控制台会按预期打印数组。但是当我运行第二个变体时,控制台声称该数组未定义。有人可以解释为什么吗?

function tipCalculator(bill){
    var parcentage;

if (bill < 50){
    parcentage = .2;
}else if (bill >= 50 && bill < 200) {
    parcentage = .15;
}else{
    parcentage = .1;
}
return parcentage * bill;
};


var bills = [124 , 48, 205];
var tips = [tipCalculator(bills[0]), 
        tipCalculator(bills[1]),
        tipCalculator(bills[2])];

console.log(tips)

function tipCalculator (bill){


    var twentyPercent = bill * 0.2;
    var fifteenyPercent = bill * 0.15;
  var tenPercent = bill * 0.1;

if (bill < 50 ) {
    console.log ('Waiter will get 20% of the bill which is ' + 
twentyPercent);
} else if ( bill >= 50 && bill < 201) {
    console.log( 'Waiter will get 15% of the bill which is ' + 
fifteenyPercent);
} else if ( bill > 200) {
    console.log(' Waiter will get 10% of the  bill which is ' + tenPercent);
} else{
    console.log('Waiter won\'t get any tip' );
}

};

var bills = [124 , 48, 205];
var tips = [tipCalculator(bills[0]), 
        tipCalculator(bills[1]),
        tipCalculator(bills[2])];

console.log(tips)

标签: javascript

解决方案


你的函数需要返回一些东西:

 function tipCalculator(bill) {
  var twentyPercent = bill * 0.2;
  var fifteenPercent = bill * 0.15;
  var tenPercent = bill * 0.1;

  if (bill < 50) {
    console.log("Waiter will get 20% of the bill which is " + twentyPercent);
    return twentyPercent;
  } else if (bill >= 50 && bill < 201) {
    console.log("Waiter will get 15% of the bill which is " + fifteenPercent);
    return fifteenPercent;
  } else if (bill > 200) {
    console.log(" Waiter will get 10% of the  bill which is " + tenPercent);
    return tenPercent;
  }
}

var bills = [124, 48, 205];
var tips = [
  tipCalculator(bills[0]),
  tipCalculator(bills[1]),
  tipCalculator(bills[2])
];

console.log(tips);

推荐阅读