我正在做一个 MEAN 堆栈项目,并且有一个如下所示的数组:
savings: any = [300, 450, 350, 500]
我还有一个名为 savings_bf 的变量,它是从具有以下值的数据库中检索到的储蓄。
savings_bf = 15000
我想用 typescript 写一些代码来获取运行总计,将 savings_bf 计入计算,并用 HTML 显示输出。
正如我所说,这是针对使用 Typescript 3.5.3 的 MEAN 堆栈应用程序。输出在控制台上按预期工作,但问题是在前端复制输出。
我目前的代码是:
this._savings_total = +this.savings.reduce((result, a) => {
var savings_amount = a.savings_amount;
return result + savings_amount;
}, this.savings_bf);
,并以 html 格式显示输出;
<p>{{_savings_amount}}</p>
预期的 HTML 输出应该是:
15300,15750,16100,16600,
but the actual output is the final value 16600
最佳答案
您的代码中的问题是您在每次迭代中都覆盖了 this_savings_bf 的值,您应该简单地映射这些值并使用一个变量来跟踪最后添加的值
let savings = [300, 450, 350, 500]
let savings_bf = 15000
let temp = savings_bf
let final = savings.map(v => temp += v)
console.log(final)
或者您可以简单地在每次迭代中使用 forEach 构建 html 字符串,并在循环结束时添加到所需位置
let savings = [300, 450, 350, 500]
let savings_bf = 15000
let html = ''
savings.forEach(v=>{
savings_bf += v
html += `<p>${savings_bf}</p>`
})
document.getElementById('test').innerHTML = html
<div id='test'/>
What if i intend for my output to begin with the initial value of savings_bf
let savings = [300, 450, 350, 500]
let savings_bf = 15000
let html = ''
savings.forEach(v => {
html += `<p>${savings_bf}</p>`
savings_bf += v
})
html += `<p>${savings_bf}</p>`
document.getElementById('test').innerHTML = html
<div id='test' />
关于javascript - 如何从 Javascript/Typescript 中的数组对象计算运行总计并使用 HTML 在每个实例中显示输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57737404/