Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解析段落中的所有数字并在JavaScript中求和_Javascript_Html_Arrays_Sum - Fatal编程技术网

解析段落中的所有数字并在JavaScript中求和

解析段落中的所有数字并在JavaScript中求和,javascript,html,arrays,sum,Javascript,Html,Arrays,Sum,我正在做下面的JS练习,其中我需要解析给定段落中的所有数字,然后对所有这些数字求和 函数get_sum(){ 设s=document.getElementById('pc').textContent; 让matches=s.match(/(\d+/); 设和=0; for(设i=0;i

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

函数get_sum(){ 设s=document.getElementById('pc').textContent; 让matches=s.match(/(\d+/); 设和=0; for(设i=0;i

个人计算机
处理器的成本为9000英镑。
主板的价格是15000美元。存储卡是6000。
显示器的价格是7000美元。硬盘的价格是4000美元。
其他物品的费用是6000英镑

求和
此处:

    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);
    }
函数get_sum(){ 设s=document.getElementById('pc').textContent; 设matches=s.match(/(\d+)/g); 设和=0; for(设i=0;i 为全局添加了
g


添加了
Number()
,因为您得到了字符串…

只是正则表达式中的一个小更改

<!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英镑

求和

函数get_sum(){
设s=document.getElementById('pc').textContent;
设matches=s.match(/\d+/g);
设和=0;
for(设i=0;i
const pc=document.querySelector(“pc”);
const totalBtn=document.querySelector(“#btn total”);
totalBtn.addEventListener(“单击”,e=>{
const prices=pc.innerText.match(/\d+/g);
const total=prices.reduce(
(总计,价格)=>(+价格)+总计,0
);
控制台日志(总计);
});
处理器的成本是9000英镑。主板的价格是15000美元。存储卡是6000。显示器的价格是7000美元。硬盘的价格是4000美元。其他物品的费用是6000英镑


计算总数
@iAmOren为什么是全局的?这有什么必要?@Sherlock,无论发生什么情况,而不仅仅是第一次。我希望这对你有用——如果是,请选择并投票给我的答案!当你复制他们的作品时,至少要有礼貌地相信他们。你是认真的吗?请检查我发布的时间和我可以提出的相同要求。
<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>