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)
解决方案
你的函数需要返回一些东西:
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);
推荐阅读
- reactjs - 使用 React-table 根据元数据过滤行
- python - 使用任何 python 库从宏 excel 调用中获取单元格值到另一个工作表
- javascript - 后台切换分两部分
- reactjs - 在 axios.post 之后属性保持未定义
- reactjs - 由于 Typescript 枚举,Next.js 在 Safari 中呈现空白屏幕
- python - Django - MongoDb - GraphQL 查询返回一个空数组
- datepicker - Nativescript RadDataForm DatePicker 编辑器将样式更改为轮子
- amazon-web-services - 当主体设置为 aws lambda.amazonaws.com 时访问被拒绝
- json - Serilog 不解析文件名模板
- android - 颤振 - “无法找到 Android SDK。”