简体   繁体   English

使用For循环进行Javascript计算

[英]Javascript Calculation Using For Loop

I'm sure that this is simple, but the solution is eluding me. 我确信这很简单,但解决办法是让我不知所措。 I want to write a function that will result in: 1000 + 1001 + 1002 + 1003 + 1004 (so I'll output 5010) 我想写一个函数将导致:1000 + 1001 + 1002 + 1003 + 1004(所以我输出5010)

I have a form where the user inputs a number x (1000 in this case) and a number of times it will iterate y (5 in this case) 我有一个表单,用户输入一个数字x(在这种情况下为1000)和多次迭代y(在这种情况下为5)

I know that I need to store the value each time through in var total, but I'm not quite getting it. 我知道我需要每次都存储整个值,但是我还没有得到它。

I have this so far: 到目前为止我有这个:

function baleTotal(){
  var x = document.addBale.strt.value;
  var y = document.addBale.baleNum.value;
  var calc = Number(x);
  total = 0;

  for (var y; y > 0; y--) {
   calc++;
  }              

  document.addBale.result.value = total;
}

You're not actually adding to your total. 你实际上并没有增加你的总数。 This does the calculation given the base and the number of iterations and returns the result, rather than operating directly on the DOM. 这将根据基数和迭代次数进行计算并返回结果,而不是直接在DOM上运行。

function baleTotal(base, iterations) {
    var total = 0;
    for (i=0; i<iterations; i++) {
        total += (base + i);
    }
    return total;
}

console.log(baleTotal(1000, 5));

You are not doing anything with total and also you are redeclaring y. 你没有做任何事情,你也正在重新宣布你。 Try this: 尝试这个:

function baleTotal(){
  var x = document.addBale.strt.value;
  var y = document.addBale.baleNum.value;
  var calc = Number(x);
  total = 0;

  for (; y > 0; y--) {
   total += calc + y;
  }              

  document.addBale.result.value = total;
}

Not tested but should work. 没有测试但应该工作。

Is this more or less what you mean? 这或多或少是你的意思吗?

function baleTotal(){
  var x = document.addBale.strt.value;
  var y = document.addBale.baleNum.value;
  total = 0;

  for (var i = 0; i < y; i++) {
   total += x + i;
  }             

  document.addBale.result.value = total;
}

I think this is what you're looking for. 我想这就是你要找的东西。

function baleTotal(){
  total = 0;
  for (var i = 0; i < document.addBale.baleNum.value; ++i) {
    total += document.addBale.strt.value + i;
  }
  document.addBale.result.value = total;
}

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

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