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

JavaScript如何将数组1的字母替换为数组2对应数值并计算总和

错误原因

你写的代码存在3个核心问题:

  • JS字符串的replace方法不支持直接传入数组作为匹配/替换参数,原有的替换逻辑完全不生效
  • filter是数组过滤API,用来筛选符合条件的元素,不能用来做值替换
  • map里的ele + ele逻辑是字符重复拼接,和需求完全不符

正确实现代码

let word = "محمد";
let search = ['ا', 'ب', 'ج', 'د', 'ه', 'و', 'ز', 'ح', 'ط', 'ي', 'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر', 'ش', 'ت', 'ث', 'خ', 'ذ', 'ظ', 'ض', 'غ'];
let replace = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100', '200', '300', '400', '500', '600', '700', '800', '900', '1000'];

if (word.trim() === "") {
  document.write('the field is empty');
} else {
  let total = 0;
  // 拆分字符串为单个字符遍历
  word.split("").forEach(char => {
    // 查找当前字符在search数组的索引
    const idx = search.indexOf(char);
    if (idx !== -1) {
      // 拿到对应替换值转成数字
      const num = Number(replace[idx]);
      // 打印字符和对应数值
      console.log(`${char} ${num}`);
      // 累加总和
      total += num;
    }
  });
  // 打印空行和总和
  console.log('');
  console.log(`total = ${total}`);
}

输出结果

和你给出的预期完全一致:

م 40
ح 8
م 40
د 4

total = 92

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:36:00