首页 > 解决方案 > 解析段落中的所有数字并在 JavaScript 中求和

问题描述

我正在做以下 JS 练习,其中我需要解析给定段落中的所有数字,然后对所有这些数字求和。

function get_sum() {
    let s = document.getElementById('pc').textContent;
    let matches = s.match(/(\d+)/);
    let sum = 0;
    for(let i = 0; i < matches.length; ++i) {
        sum += matches[i];
    }
    console.log(sum);
}
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>PC</title>
  </head>
  <body>
  <p id="pc"> The cost of the processor is 9000.
      The cost of the motherboard is 15000. The memory card is 6000.
      The price of the monitor is 7000. The hard disk price is 4000.
      Other item's cost is 6000. </p>

  <button type="button" onclick='get_sum()'>Get Sum</button>
  </body>
  </html>

输出应该是表达式的评估 9000+15000+6000+7000+4000+6000 即 47000

标签: javascripthtmlarrayssum

解决方案


这里:

    function get_sum() {
        let s = document.getElementById('pc').textContent;
        let matches = s.match(/(\d+)/g);
        let sum = 0;
        for(let i = 0; i < matches.length; ++i) {
            sum += Number(matches[i]);
        }
        console.log(sum);
    }

g为全局添加,添加
Number()因为您获得字符串...


推荐阅读