使用 Javascript 从文本区域中的每个换行符添加数字

Add Numbers from Each Line Break in Textarea with Javascript

我在文本区域中有以下内容:

link|10000
link|25000
link|58932

我需要删除“|”之前的字符在每一行上得到所有数字的总和

任何帮助将不胜感激!

使用 String#match method and calculate the sum using Array#reduce 方法从值中获取所有数字。

var ele = document.getElementById('text');

// get the text area value 
var res = ele.value
  // get all digits combinations , if you want decimal number then use /\d+(\.\d+)?/g
  .match(/\d+/g)
  // iterate and calculate the sum
  .reduce(function(sum, v) {
    // parse the number and add it with previous value
    return sum + Number(v);
    // set initial value as 0
  }, 0);

console.log(res);
<textarea id="text">link|10000 link|25000 link|58932
</textarea>

另一个解决方案:

  function myFunction() {
document.getElementById("demo").innerHTML = document.getElementById("myTextarea").value.split("link|").map(Number).reduce(function(a, b){return  a+b; });
}
Calculate:<br>
<textarea id="myTextarea">
link|10000
link|25000
link|58932</textarea>

<p>Click the button to calculate.</p>

<button type="button" onclick="myFunction()">Calculate it</button>
 <p id="demo"></p>

一个简短的解决方案:

// Gets textarea content
var myTextareaText = document.getElementById('my-textarea-id').value;

// Uses array functions to simplify the process
let sum = myTextareaText.split('\n').map(x=>x.split('|')[1] * 1).reduce((a,b)=>a+b);

// Logs de result
console.log(sum);

做了什么:

1) 换行符:myTextareaText.split('\n')
2) 对于每一行,以“|”分隔,获取第二项并将其转换为数字:map(x=>x.split('|')[1] * 1)
3)对每个元素求和:reduce((a,b)=>a+b)