简体   繁体   English

将函数的结果推入空数组

[英]push the result of a function into an empty array

I have an array of bills and an empty array for tips.我有一个账单数组和一个用于提示的空数组。 I'm trying to call a tipcalculator function within a for loop so I can calculate the tips of each one of the bills in the bills array, store that result in the empty tips array.我正在尝试在 for 循环中调用一个 tipcalculator 函数,以便我可以计算 bills 数组中每一张账单的小费,并将结果存储在空的 tips 数组中。 Is this possible to be done?这是可能的吗?
Thanks谢谢

 var bills = [123,145,12,44]; var tips = []; function calculateTips(bill){ let tip; if(bill<10){ tip = .2; } if(bill>=10 && bill <20){ tip = .10; } else { tip = 0.1; } return tip * bill; for(var i=0; i<bills.length; i++){ var temp = calculateTips(bills[i]); tips.push(temp); } };

Your loop needs to be outside of the function.您的循环需要在函数之外。 As the documentation says :正如文档所说

The return statement ends function execution and specifies a value to be returned to the function caller. return语句结束函数执行并指定要返回给函数调用者的值。

 var bills = [123,145,12,44]; var tips = []; function calculateTips(bill){ let tip; // Since the bill will only fall into one of your tests // use else if, rather than an if followed by another if if(bill < 10){ tip = .2; } else if(bill >= 10 && bill < 20){ tip = .10; } else { tip = 0.1; } // once a function reaches a return statement // it will return the specified value (if any) // and then stop processing the function. return tip * bill; } for(var i=0; i<bills.length; i++){ var temp = calculateTips(bills[i]); tips.push(temp); } console.log(tips);

There is no difference between tip=.10 and tip=0.1 . tip=.10tip=0.1之间没有区别。 And you can shorten your script considerably, see below.你可以大大缩短你的脚本,见下文。

 const calculateTips=bill=>((bill>=10?.1:.2)*bill).toFixed(2); var bills = [123,145,12,44,8]; let tips=bills.map(calculateTips); console.log(tips);

Fun fact: Your formula leads to higher tips for 8$ than for 12$ bills.有趣的事实:你的公式导致 8 美元的小费比 12 美元的账单更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM