简体   繁体   English

如何从Javascript / Typescript中的数组对象计算运行总计并使用HTML在每个实例中显示输出?

[英]How to calculate running total from an array object in Javascript/Typescript and display output at every instance using HTML?

I am working on a MEAN stack project and have an array that looks like this: 我正在研究MEAN堆栈项目,并且有一个看起来像这样的数组:

savings: any = [300, 450, 350, 500]

I also have a variable called savings_bf, which is savings brought forward retrieved from a DB with the value below. 我也有一个名为Savings_bf的变量,它是从数据库中带出的储蓄值,其值如下。

savings_bf = 15000 

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. 我想用打字稿写一些代码来获取运行总计,将Savings_bf纳入计算中,并用HTML显示输出。

As i have stated, this is for a MEAN stack application using Typescript 3.5.3. 如我所说,这是使用Typescript 3.5.3的MEAN堆栈应用程序。 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);

,and displaying the output in html as; ,并以html格式显示输出;

<p>{{_savings_amount}}</p>

The expected HTML output should be: 预期的HTML输出应为:

15300,15750,16100,16600,
but the actual output is the final value 16600

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 代码中的问题是您在每次迭代中都覆盖了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) 

Or you can simply use forEach build html string in each iteration and at the end of loop add to desired place 或者,您可以在每次迭代中简单地使用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 如果我打算让输出以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' /> 

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

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