需要帮助以非常简单的javascript总计运行 [英] Need help with very simple running total for javascript

查看:52
本文介绍了需要帮助以非常简单的javascript总计运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如此简单的问题,我似乎无法弄清楚.如果这很明显,我只是在学习,很抱歉.

So real simple problem that I just can't seem to figure out. I'm just learning so sorry if this is obvious.

必须出7桌,最后给出总成绩.这就是我所拥有的:

Has to out put 7 times tables and give a running total at the end. Here's what I have:

document.write("<h3>7 times tables</h3>");
document.write("<ul>");
i=1;
seven=7;

  while(i < 13) {
     Seven= i * seven;
     document.writeln("<li>" + i + " times 7 = " + Seven);
     var result=new Array(6)
     result[1]=Seven;
     i++;
  }

document.writeln("</ul>");
document.write("<strong>The sum do far is"+result[1]+"</strong>");

谢谢

推荐答案

您要在循环中重新声明您的 result 数组,因此每次迭代都将清除先前的计算并从头开始.将 var result = new Array(6)移动到 while(i< 13)之前,然后重试:

You're redeclaring your result array within the loop, so each iteration wipes out the previous calculations and starts you over from scratch. move var result=new Array(6) to immediately before the while(i<13) and try again:

var result = new Array(6);
while(i < 13) {
   ...
}

但是,这引出了一个问题……为什么要使用数组"?您只是使用它来进行总运行,因此只需使用一个简单的int:

However, this begs the question of ... "why use an array"? You're simply using it to do a running total, so just use a simple int:

var result = 0;
while(i < 13) {
   result = result + (i * 7);  // or simply: result += i * 7;
   ...
}

这是一个小提琴 http://jsfiddle.net/zeYQm/1/

这篇关于需要帮助以非常简单的javascript总计运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆