【问题标题】:How to find sum of integers in a string using JavaScript如何使用 JavaScript 查找字符串中的整数和
【发布时间】:2016-08-30 20:41:20
【问题描述】:

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

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

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
}

【问题讨论】:

  • \\D 不是有效的正则表达式。你添加的是字符串而不是数字
  • 您是否尝试过单步执行以查看中断的位置?
  • 你有没有checked your console for errors?你说忽略语法但是如果语法错误,程序根本不会运行。
  • 缩进你的代码! var patrn 应该是:var patrn = "\\D"
  • 当你说“不工作”时,实际发生了什么?您是否收到错误或与预期不符的输出?

标签: javascript expression sum-of-digits


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    你有一些错误:

    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/

    【讨论】:

    • 所以警报返回 6,但目标是返回将导致 21 的 str。您能解释一下警报的原因吗?
    【解决方案3】:
    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");

    【讨论】:

    • 您需要使用 parseInt,因为将字符串加在一起不会进行转换,因此 '2' + '2' 将是 '22'
    猜你喜欢
    • 1970-01-01
    • 2010-12-10
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多