Javascript 循环遍历数组并返回所有值的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7328000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:49:36  来源:igfitidea点击:

Loop through array and return sum of all values

javascriptarraysloopssum

提问by tc03

What I want to do is have numbers inputted by user and the sum of the numbers returned. My logic is as follows:

我想要做的是用户输入的数字和返回的数字总和。我的逻辑如下:

  1. User inputs string
  2. String is split to array
  3. Loop through array and sum all numbers
  4. Return sum
  1. 用户输入字符串
  2. 字符串被拆分为数组
  3. 循环遍历数组并对所有数字求和
  4. 返还金额

And here is the code I have so far:

这是我到目前为止的代码:

<script type='text/javascript'>

var val=document.getElementById('userInput').value;
var temp=val.split(" ");

function sum() {
    for(var i=0, MISSING THIS BIT

    document.getElementById('resultSum').innerHTML=MISSING THIS BIT;
}

</script>

<form name="input">
    <textarea name="userInput" rows=20 cols=20></textarea>
    <input name="Run" type=Button value="run" onClick="sum()">
<form name="resultSum"><input type=Text>

I admit with humility that this is mostly probably wrong and appreciate anybody's time and effort.

我谦虚地承认这很可能是错误的,并感谢任何人的时间和努力。



UPDATE: I have done as suggested and I get the following error on my code below:

更新:我已按照建议进行操作,但在下面的代码中出现以下错误:

Message: 'document.getElementById(...)' is null or not an object Line: 16 Char: 1 Code: 0

消息:'document.getElementById(...)' 为空或不是对象行:16 字符:1 代码:0

<html>

<script type='text/javascript'>

function sum(){
    var val = document.getElementById('userInput').value;
    var temp = val.split(" ");

    var total = 0;
    var v;
    for(var i = 0; i < temp.length; i++) {
        v = parseFloat(temp[i]);
        if (!isNaN(v)) total += v;
    }

    document.getElementById('resultSum').innerHTML=total;

}

</script>

<form name="input">
    <textarea name="userInput" rows=20 cols=20></textarea>
    <input name="Run" type=Button value="run" onClick="sum()">
    <form name="resultSum"><input type=text>
<html>

Any suggestions? Thanks to all for being comprehensive - I have read both examples and understand the process now!

有什么建议?感谢所有人的全面性 - 我已经阅读了两个示例并且现在理解了这个过程!

回答by loganfsmyth

You want a basic loop to convert and add each item.

您需要一个基本循环来转换和添加每个项目。

I have also cleaned up your HTML a ton. You didn't have any proper closing tags. I have also changed all of the 'name' attributes to 'id' attributes so that 'getElementById' would work properly, which I missed on my first pass.

我还大量清理了您的 HTML。你没有任何合适的结束标签。我还将所有“name”属性更改为“id”属性,以便“getElementById”可以正常工作,这是我在第一次通过时错过的。

<html>
  <head>
    <script type='text/javascript'>
      function sum(){ 
        var val = document.getElementById('userInput').value;
        var temp = val.split(" ");
        var total = 0;
        var v;
        for(var i = 0; i < temp.length; i++) {
          v = parseFloat(temp[i]);
          if (!isNaN(v)) total += v; 
        } 
        document.getElementById('resultSumValue').value = total; 
      } 
    </script>
  </head>
  <body>
    <form id="input">
      <textarea id="userInput" rows=20 cols=20></textarea> 
      <input id="Run" type=Button value="run" onClick="sum()" />
    </form>

    <form id="resultSum">
      <input id="resultSumValue" type="text" />
    </form>
  </body>
</html>

This will also ignore any values that are 'NaN' (Not a Number).

这也将忽略任何为“NaN”(非数字)的值。

If you want the numbers to only be integers (no decimals), change parseFloat to parseInt.

如果您希望数字仅为整数(无小数),请将 parseFloat 更改为 parseInt。

回答by spike

Here is an outline, but I think it's worth writing it yourself to learn.

这里有一个大纲,但我认为值得自己写出来学习。

回答by kennebec

<html>
<head>
<title>sum input</title>
<style>
p, textarea,input{font-size:24px}
textarea,input{text-align:right}
</style>
<script>
function sum(){
    var val= document.getElementById('userInput').value.replace(/^\D+|D+$/g,'');    
    document.getElementById('resultSum').value= eval(val.replace(/\D+/g,'+'));

}
</script>
</head>
<body>
<p>Enter a series of numbers :<br>
<textarea id="userInput" rows="10" cols="10"></textarea><br>
<input id="Run" type="button" value="Sum" onClick="sum()">
<input id="resultSum" type="text" readOnly>
</p>
</body>
</html>

回答by cp3

First start by declaring a variable set to 0 before the for loop. Iterate over each element in the array (array.length) adding to the variable you set before the for loop.

首先在 for 循环之前声明一个设置为 0 的变量。迭代数组 (array.length) 中的每个元素,添加到您在 for 循环之前设置的变量。