-1

我使用正则表达式创建了一个函数,然后通过将前一个总数添加到数组中的下一个索引来迭代数组。

我的代码不起作用。我的逻辑有问题吗?忽略语法

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
}
4

3 回答 3

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

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

您还缺少代码末尾的右括号。


一个更简单的解决方案是查找字符串中的所有整数,将它们转换为数字(例如使用+运算符)并将它们相加(例如使用reduce操作)。

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

于 2016-08-30T20:49:44.217 回答
1

你有一些错误:

改变var patrn = \\D_var patrn = "\\D"

使用parseInttotal += parseInt(tot);

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 += parseInt(tot); // add the previous total to the new total
})
return total; // return the total once finished
}

alert(sumofArr(["1", "2", "3"]));

https://jsfiddle.net/efrow9zs/

于 2016-08-30T20:49:35.293 回答
0
function sumofArr(str) {
 var tot = str.replace(/\D/g,'').split('');
   return  tot.reduce(function(prev, next) {
   return parseInt(prev, 10) + parseInt(next, 10);
});}

sumofArr("12sf0as9d");

于 2016-08-30T21:06:01.747 回答