最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

cumulative sum - Need help with very simple running total for javascript - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited May 24, 2011 at 19:26 Chad 19.6k4 gold badges53 silver badges75 bronze badges asked May 24, 2011 at 19:23 SeanSean 111 silver badge2 bronze badges 1
  • Please provide better sample code. – roberkules Commented May 24, 2011 at 19:27
Add a ment  | 

4 Answers 4

Reset to default 3

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/zeYQm/1/

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

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.

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

发布评论

评论列表(0)

  1. 暂无评论