gpt4 book ai didi

javascript - 尝试返回字符串中数字的总和。如果字符串是 "99Hello1"输出是 100,如果是 "9hello9"答案是 18。遇到无知的错误

转载 作者:行者123 更新时间:2023-12-01 02:42:42 24 4
gpt4 key购买 nike

function NumberSearch(str) {
var arr = str.split("");
var sum = 0;
var twoDigit = [];
var two;
var res = [];
var arrFormat = preProcess(arr);
console.log(arrFormat);
//this function returns an array that has all numbers from the string
function preProcess(ele) {
for (var i = 0; i < ele.length; i++) {
if (typeof ele[i] === 'number' && typeof ele[i + 1] === 'number') {
twoDigit.push(ele[i], ele[i + 1]);
two = twoDigit.join("");
res.push(two);
} else {
if (typeof ele[i] === 'number' && typeof ele[i + 1] !==
'number') {
res.push(ele[i]);
}
}
}
return res;
}
for (var k = 0; k < arrFormat.length; k++) {
sum = sum + arrFormat[k];
}
return sum;
}

console.log(NumberSearch("99Hello1"));

我试图通过首先循环字符串并收集所有数字然后求和来解决问题。

最佳答案

您可以使用正则表达式来匹配数字并减少获得的数组。

function sum(string) {
return (string.match(/\d+/g) || []).reduce(function (a, b) { return a + +b; }, 0)
}

console.log(['99hello1', '9hello9'].map(sum));

关于javascript - 尝试返回字符串中数字的总和。如果字符串是 "99Hello1"输出是 100,如果是 "9hello9"答案是 18。遇到无知的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com