如何循环计算生成最多10条记录并表格展示,按起始年触发costOne/costTwo计算
解决方案
问题1:循环生成10条记录并渲染网页表格
实现逻辑如下:
- 用输入的初始Amount作为第一条记录的计算基数
- 控制循环次数为9次,加上首条记录总共生成10条,每一轮的计算都以上一条记录的输出结果作为当前轮的输入基数
- 计算完成后通过拼接HTML字符串的方式渲染为网页表格,前端框架用户也可以直接用列表绑定语法渲染
示例代码(JS实现):
// 读取输入参数 const inputParams = { amount: 1500, inputOne: 10, inputTwo: 5, startingYear: 4, percentage: 15 } // 存储所有计算记录的数组 const records = [] // 初始化第一条记录 let prevRecord = { year: 1, baseAmount: inputParams.amount, costA: 0, costB: 0, finalAmount: inputParams.amount } records.push(prevRecord) // 循环生成剩余9条记录 for(let i = 2; i <= 10; i++) { const currentBase = prevRecord.finalAmount let costA = 0, costB = 0 // 成本计算逻辑留空,问题2会补充 const finalAmount = currentBase - costA - costB + (currentBase * inputParams.percentage / 100) const currentRecord = { year: i, baseAmount: currentBase, costA, costB, finalAmount } records.push(currentRecord) prevRecord = currentRecord } // 渲染为网页表格 const tableHtml = ` <table border="1" cellpadding="8"> <thead> <tr><th>年份</th><th>基数金额</th><th>costA</th><th>costB</th><th>最终金额</th></tr> </thead> <tbody> ${records.map(item => ` <tr> <td>${item.year}</td> <td>${item.baseAmount.toFixed(2)}</td> <td>${item.costA.toFixed(2)}</td> <td>${item.costB.toFixed(2)}</td> <td>${item.finalAmount.toFixed(2)}</td> </tr> `).join('')} </tbody> </table> ` // 插入到页面指定容器 document.getElementById('result-box').innerHTML = tableHtml
问题2:起始年生效的判断条件设置
核心判断逻辑为:生成每条记录时,判断当前记录的年份是否大于等于输入的起始年,满足条件才执行costOne、costTwo的计算逻辑,不满足则成本值直接设为0即可。
将问题1代码中的成本计算部分替换为如下逻辑即可:
let costA = 0, costB = 0 // 核心判断条件 if(i >= inputParams.startingYear) { // 此处替换为你实际的costOne、costTwo计算逻辑,示例用inputOne、inputTwo作为比例计算 costA = currentBase * inputParams.inputOne / 100 costB = currentBase * inputParams.inputTwo / 100 }
输入参数对应输出样例
| 年份 | 基数金额 | costA | costB | 最终金额 |
|---|---|---|---|---|
| 1 | 1500.00 | 0.00 | 0.00 | 1725.00 |
| 2 | 1725.00 | 0.00 | 0.00 | 1983.75 |
| 3 | 1983.75 | 0.00 | 0.00 | 2281.31 |
| 4 | 2281.31 | 228.13 | 114.07 | 2281.31 |
| 5 | 2281.31 | 228.13 | 114.07 | 2281.31 |
| 6 | 2281.31 | 228.13 | 114.07 | 2281.31 |
| 7 | 2281.31 | 228.13 | 114.07 | 2281.31 |
| 8 | 2281.31 | 228.13 | 114.07 | 2281.31 |
| 9 | 2281.31 | 228.13 | 114.07 | 2281.31 |
| 10 | 2281.31 | 228.13 | 114.07 | 2281.31 |
内容的提问来源于stack exchange,提问作者user17131817
相关产品推荐
相关产品推荐

