为什么控制台声称数组未定义?

时间:2018-08-21 15:13:54

标签: javascript

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

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)

2 个答案:

答案 0 :(得分:1)

您的函数需要返回一些信息:

 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);

答案 1 :(得分:0)

在第二个代码中,您的tipCalculator函数缺少return语句,因此tip数组未正确填充。