() 用js编写一个函数,从一个任意字符串中提取所有的数字,然后将它们添加在一起

注意不能用正则表达式. 使用的知识点只能是js的语法范围.

先谢过了

例如:

Input: “We have 30 apples will be handed out to 10 students who need it, containing 5 foreigners ”.
Output: 30 + 10 + 5 = 45

var str=We have 30 apples will be handed out to 10 students who need it, containing 5 foreigners; var sum = evalstr.match/d+/g.join+; console.logsum; // => 45 // 不用正则 var sumNoPattern = evalstr.split .filterfunctionitem{
return item-0===+item
}.join+; console.logsumNoPattern; // => 45

typeof arr[i] === number

把字符串挨着扫描一遍不就完了……

function char2numstr{ let num = [], ans = 0, index = -1; forlet i = 0; i < str.length + 1; i++ { const now = parseIntstr[i]; ifi < str.length && str[i] ===. || now !== NaN && now < 10 && now > -1 { ifindex === -1 { index = i; } } else ifindex !== -1 { num.pushparseFloatstr.substringindex, i; ans += num[num.length - 1]; index = -1; } } returnnum.join" + " + " = " + ans;
}

var str = We have 30 apples will be handed out to 10 students who need it, containing 5 foreigners;

 var arr = [],sum = 0; arr = str.split ; forvar i = 0; i < arr.length; i++{ if!isNaNparseIntarr[i]{ sum += parseIntarr[i]; } } console.logsum;

//需要处理的字符串
var str = We have 30 apples will be handed out to 10 students who need it, containing 5 foreigners;
//处理函数
var onlyNumpluse = functionstrArg{ //用空格将字符串截成数组 var strArr = strArg.split , sum = 0; //循环判断非NaN的value相加 forvar i=0,len=strArr.length;i<len;i++{ if!isNaNparseIntstrArr[i]{ sum += parseIntstrArr[i]; } } //返回结果 return sum;
}
//调用
onlyNumplusestr

//要求:从一串随机字符串中提取数字并相加
//要求:数字必须是连续数字,如ab30cd,必须提取30
//TODO:此方法未处理小数,如ab0.23cd,会提取23
function str2numoldStr { if oldStr == { console.logstring is required; } else { //先去掉字符串的空格,再在首位分别加上‘aaa’和‘bbb’; //首尾加上非数字字符串是为了防止原字符串首尾是数字而导致的提取错误; var str = aaa + oldStr.replace/ /g, + bbb; var notNumIndexArr = [];//非数字字符的序号组成的数组 var newArrFromStr = [];//由数字组成的数组 var ArrForSum;//剔除newArrFromAtr中的空字符串后的纯数字数组 var sum = 0;//输出的总和 //提取非数字字符串的序号 for let i = 0; i < str.length; i++ { if isNaNstr.charAti { notNumIndexArr.pushi; } } //最重要的一步 //提取非数字字符串的序号中间的数字 for let i = 0; i < notNumIndexArr.length; i++ { newArrFromStr.pushstr.substringnotNumIndexArr[i], notNumIndexArr[i + 1].substring1;//首字符是字母,需要从第二个字符提取 } //console.lognotNumIndexArr; //console.lognewArrFromStr; //剔除数组中的空字符串 ArrForSum = newArrFromStr.filterfunction val { return val !== ; }; //不需要剔除前几位是0的数字,如提取出来是003,相加时会当成3相加 //求和 for let i = 0; i < ArrForSum.length; i++ { sum += parseIntArrForSum[i]; } return sum; }
} var str = We have 30 apples will be handed out to 10 students who need it, containing 5 foreigners;
console.logstr2numstr;

发表评论

电子邮件地址不会被公开。 必填项已用*标注