Разберите все числа в абзаце и просуммируйте их в JavaScript - PullRequest
0 голосов
/ 09 июля 2020

Я выполняю следующее упражнение 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

Ответы [ 3 ]

3 голосов
/ 09 июля 2020

const pc = document.querySelector("#pc");
const totalBtn = document.querySelector("#btn-total");

totalBtn.addEventListener("click", e => {
  const prices = pc.innerText.match(/\d+/g);

  const total = prices.reduce(
    (total, price) => (+price) + total, 0
  );

  console.log(total);
});
<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 id="btn-total">Calculate Total</button>
3 голосов
/ 09 июля 2020

Здесь:

    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(), потому что вы получаете строки ...

0 голосов
/ 09 июля 2020

Небольшое изменение в регулярном выражении.

<!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>
<script>
    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 += parseInt(matches[i]);
        }
        console.log(sum);
    }
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...