我有字符串: const text =“我今天花了 1430 美元”
我需要使用 for 循环从末尾获取金额 1430 禁止:不要使用 parseInt、parseFloat、Number、+str、1 * str、1 / str、0 + str 等
限制:1 个 for 循环,charCodeAt
我尝试解决这个问题,数字以相反的顺序书写是有道理的。在不使用反向(或其他本机方法)或额外的循环\函数的情况下如何避免这种情况?
function searchAmount(str) {
let amount = 0;
for (let i = str.length - 1; i >= 0; i--) {
const charCode = str.charCodeAt(i);
if (charCode >= 48 && charCode <= 57) {
amount = amount * 10 + (charCode - 48);
}
}
return amount;
}
console.log(searchAmount(text));
您需要根据找到的数字的“位置”,将找到的数字乘以 10^0、10^1、10^2 等,而不是到目前为止已经计算出的金额。
您可以通过保留乘法因子来做到这一点,从
1
开始,每次添加数字后乘以 10
:
function searchAmount(str) {
let amount = 0,
factor = 1;
for (let i = str.length - 1; i >= 0; i--) {
const charCode = str.charCodeAt(i);
if (charCode >= 48 && charCode <= 57) {
amount += (charCode - 48) * factor;
factor *= 10;
}
}
return amount;
}
console.log(searchAmount("I spent 1430 USD today"));