如何使用JavaScript查找字符串中的整数和 [英] How to find sum of integers in a string using JavaScript

查看:83
本文介绍了如何使用JavaScript查找字符串中的整数和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有正则表达式的函数,然后通过将前一个总数与下一个索引相加来遍历整个数组.

I created a function with a regular expression and then iterated over the array by adding the previous total to the next index in the array.

我的代码无法正常工作.我的逻辑不对吗?忽略语法

My code isn't working. Is my logic off? Ignore the syntax

function sumofArr(arr) { // here i create a function that has one argument called arr
  var total = 0; // I initialize a variable and set it equal to 0 
  var str = "12sf0as9d" // this is the string where I want to add only integers
  var patrn = \\D; // this is the regular expression that removes the letters
  var tot = str.split(patrn) // here i add split the string and store it into an array with my pattern
  arr.forEach(function(tot) { // I use a forEach loop to iterate over the array 
    total += tot; // add the previous total to the new total
  }
  return total; // return the total once finished
}

推荐答案

var patrn = \\D; // this is the regular expression that removes the letters

这不是JavaScript中的有效正则表达式.

This is not a valid regular expression in JavaScript.

您还缺少代码结尾的右括号.

You are also missing a closing bracket in the end of your code.

一种更简单的解决方案是找到字符串中的所有整数,将它们转换为数字(例如,使用+运算符)并将它们求和(例如,使用reduce运算符).

A simpler solution would be to find all integers in the string, to convert them into numbers (e.g. using the + operator) and summing them up (e.g. using a reduce operation).

var str = "12sf0as9d";
var pattern = /\d+/g;
var total = str.match(pattern).reduce(function(prev, num) {
  return prev + +num;
}, 0);

console.log(str.match(pattern)); // ["12", "0", "9"]
console.log(total);              // 21

这篇关于如何使用JavaScript查找字符串中的整数和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆