You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用charCodeAt和单反向for循环提取字符串中的正确数值(禁转换方法)

从字符串末尾遍历提取数字时解决顺序反转的问题

现有字符串 const text = "I spent 1430 USD today",要求通过从末尾开始的单个for循环提取金额1430,且禁止使用parseInt、parseFloat、Number、+str等数值转换方法,仅允许使用charCodeAt和单个for循环。

尝试的代码如下:

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)); // 输出341,结果错误

问题分析

原代码的逻辑是每次把新拿到的数字放到当前结果的个位(通过amount * 10腾出个位),但因为是从后往前遍历字符串,拿到的数字顺序是0→3→4→1,最终计算出的是0*10+0=0 → 0*10+3=3 → 3*10+4=34 → 34*10+1=341,正好是原数字的反转,结果错误。

解决方法

引入一个权重变量digitPlace,用来标记当前拿到的数字对应的位数(个位、十位、百位等)。初始时digitPlace为1(对应个位),每拿到一个数字,就将它乘以digitPlace后加到结果中,然后把digitPlace乘以10,让下一个拿到的数字对应更高一位。

修改后的代码如下:

function searchAmount(str) {
  let amount = 0;
  let digitPlace = 1; // 标记当前数字的权重,初始是个位(10^0)

  for (let i = str.length - 1; i >= 0; i--) {
    const charCode = str.charCodeAt(i);

    if (charCode >= 48 && charCode <= 57) {
      const digit = charCode - 48;
      amount += digit * digitPlace;
      digitPlace *= 10; // 权重升级到下一位
    }
  }
  return amount;
}

const text = "I spent 1430 USD today";
console.log(searchAmount(text)); // 输出1430,正确

逻辑说明

  • 遍历到第一个数字(字符串末尾的0):digit=0,amount += 0*1=0,digitPlace变为10
  • 遍历到3:digit=3,amount +=3*10=30,digitPlace变为100
  • 遍历到4:digit=4,amount +=4*100=400 → 总金额430,digitPlace变为1000
  • 遍历到1:digit=1,amount +=1*1000=1000 → 总金额1430,digitPlace变为10000
  • 后续遍历到非数字字符,不做处理,最终返回1430

内容的提问来源于stack exchange,提问作者akula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:35:20