Как найти сумму целых чисел в строке, используя JavaScript
Я создал функцию с регулярным выражением, а затем перебрал массив, добавив предыдущую сумму к следующему индексу в массиве.
Мой код не работает. Моя логика выключена? Игнорировать синтаксис
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
}
3 ответа
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
you have some errors:
менять var patrn = \\D
с var patrn = "\\D"
использование parseInt
: total += 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"]));
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");