Need help with very simple running total for javascript

寵の児 提交于 2019-12-11 07:27:46

问题


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

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>");

Thanks


回答1:


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) {
   ...
}

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;
   ...
}

Here's a fiddle http://jsfiddle.net/zeYQm/1/




回答2:


document.write("<h3>7 times tables</h3>");
document.write("<ul>");
i=1;
seven=7;
var result = 0;
  for(var i = 1; i <= 13; i++){
     document.writeln("<li>" + i + " times 7 = " + (seven*i) + '</li>');   
    result += (seven*i);
  }

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



回答3:


You may also want to take a look at underscore.js, which adds some nice functional programming abilities to Javascript.

var underscore = _.noConflict();
var arr = [5, 5, 5, 5, 5];
var temp = [];
underscore.reduce(arr, function(memo, num) { 
    var value = memo + num;
    temp.push(value);
    return value; }, 0);
console.log(temp);

//Produces: 5, 10, 15, 20, 25.




回答4:


You're recreating the result array every time you go through the loop, try declaring it before the while loop.



来源:https://stackoverflow.com/questions/6115740/need-help-with-very-simple-running-total-for-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!