【发布时间】:2023-01-07 01:33:16
【问题描述】:
我不能比这个线程的标题更强调这个问题了! 我正在尝试将先前计算的函数总和保存到我之后创建的空数组中(在函数范围之外)。
我如何将所有计算出的总和保存到一个数组中,而不是仅将计算出的元素推送到数组中,下次有新元素时,前一个元素将被删除而不保存。
还!! 我想知道我是否正确编写了任务并正确使用了功能工具!
史蒂文仍在构建他的小费计算器,使用与 之前:如果账单价值在 50 到 300 之间,则给账单的 15% 的小费, 如果值不同,则小费为 20%。你的任务:
- 编写一个函数“calcTip”,将任何账单值作为输入并返回相应的小费,根据规则计算 以上(您可以查看第一个小费计算器挑战中的代码 如果你需要)。使用您最喜欢的函数类型。测试 使用帐单价值 100 的函数
- 现在让我们使用数组!所以创建一个包含下面测试数据的数组'bills'
- 创建一个数组“tips”,其中包含每个账单的小费值,该值是根据您之前创建的函数计算得出的
- 奖励:创建一个包含总值的数组“total”,因此 bill + tip 测试数据:125、555 和 44 提示:记住数组 每个位置都需要一个值,这个值实际上可以是 函数的返回值!所以你可以调用一个函数作为数组 值(所以不要先将小费值存储在单独的变量中,但是 就在新阵列中)
我的代码:
myBills = [125, 555, 44, 57, 683, 12, 991, 33, 477, 28, 1215]; const billCalc = Math.floor(Math.random() * myBills.length); const randomBill = myBills[billCalc]; let tipValue = undefined; if (randomBill >50 && randomBill <300) { tipValue = 15; } else if (randomBill <50 || randomBill >300) { tipValue = 20; } let finalTip = tipValue / 100 * randomBill; function calcTip(tip) { if (tipValue === 15) { console.log(`The bill for the table is ${randomBill}, and the tip is : ${finalTip}. The final payment is: ${randomBill + finalTip}`); } else if (tipValue === 20) { // change the rquality operator to 2 or 3 console.log(`The bill for the table is ${randomBill}, and the tip is : ${finalTip}. The final payment is: ${randomBill + finalTip}`); } } // this supposed to save the results for the tips, and to store it in the array below this line. const tipSave = calcTip(finalTip); const tipList = [21, 22, 63] tipList.push(tipSave);如果你能从我的代码中教我什么,我做错了什么,我如何简化它,让它更干净,或者我用过和不应该用的东西。
还有关于数组的问题。我非常想得到这方面的帮助。
【问题讨论】:
标签: javascript arrays function data-structures save