如何从Javascript / Typescript中的数组对象计算运行总计并使用HTML在每个实例中显示输出? [英] How to calculate running total from an array object in Javascript/Typescript and display output at every instance using HTML?
问题描述
我正在研究MEAN堆栈项目,并且有一个如下所示的数组:
I am working on a MEAN stack project and have an array that looks like this:
savings: any = [300, 450, 350, 500]
我还有一个名为Savings_bf的变量,该变量用于结转
I also have a variable called savings_bf, which is savings brought forward retrieved from a DB with the value below.
savings_bf = 15000
我想用打字稿写一些代码来获取运行总额,将Savings_bf计入计算中,并用HTML显示输出。
I would like to write some code with typescript to get the running total, factor in the savings_bf into the calculation,and display the output with HTML.
我已经说过,这是针对使用Typescript 3.5.3的MEAN堆栈应用程序。输出可以在控制台上按预期工作,但是问题是在前端复制输出。
As i have stated, this is for a MEAN stack application using Typescript 3.5.3. The output works as expected on the console, but the problem is replicating the output on the front-end.
我到目前为止的代码是:
The code i have so far is:
this._savings_total = +this.savings.reduce((result, a) => {
var savings_amount = a.savings_amount;
return result + savings_amount;
}, this.savings_bf);
,并以html格式显示输出;
,and displaying the output in html as;
<p>{{_savings_amount}}</p>
预期的HTML输出应为:
The expected HTML output should be:
15300,15750,16100,16600,
but the actual output is the final value 16600
推荐答案
代码中的问题是您在每次迭代中都覆盖了this_savings_bf的值,您应该简单地映射这些值并使用变量来保持最后添加值的跟踪
The problem in your code is you're overriding value of this_savings_bf in each iteration, You should simply map through the values and use a variable to keep track of last add value
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字符串,并在循环结束时添加到所需位置
Or you can simply use forEach build html string in each iteration and at the end of loop add to desired place
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'/>
如果我打算让输出以
Saving_bf的初始值开头
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 / Typescript中的数组对象计算运行总计并使用HTML在每个实例中显示输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!