javascript - 解析段落中的所有数字并在 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
解决方案
这里:
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()
因为您获得字符串...
推荐阅读
- python - 基于索引复制行会使行相乘而不是复制
- http - 带静态文件的 Go Gorilla mux 子路由器
- r - 如何随时避免这种情况(
) “参考更新”? - reactjs - 无法读取 null 的属性 - react.js 状态
- python-3.x - 使用 Zelle graphics.py 将点逐一更新到窗口
- javascript - 用户自己可以为他们的 RichEmbed 设置描述吗
- python - 如何在 Django Rest Framework 中加入 3 个表(仅主键)
- ios - 在 Swift 中关闭应用程序时徽章图标不更新
- css - 如何在不旋转图像的情况下旋转剪辑路径?
- php - Apache/PHP 无法在 Ampps 中启动