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

JavaScript中Map(HashMap)正确用法求助:子串判断程序改造

子串判断程序中Map使用的问题修复指导

问题描述

我想在判断子串的JavaScript程序里使用Map(即HashMap),现在有一段能正常运行但未使用Map的代码,自己尝试修改引入Map后出现了问题,希望得到相关指导。

原可运行代码

function isSubstring(string1, string2, a, b) {
  if (a == 0) return true;
  if (b == 0) return false;

  if (string1[a - 1] == string2[b - 1])
    // 注意:这里原代码有笔误,应该是b-1而非2-1
    return isSubstring(string1, string2, a - 1, 2 - 1);
  return isSubstring(string1, string2, a, b - 1);
}

let string1 = "lofri";
var punctLess = string1
  .replace(/[.,\/#!$%\^&*;:{}=\-_`~()]/g, "")
  .replace(/\s{2,}/g, " ");
let string2 = "hello, friend!";
let a = string1.length;
let b = string2.length;
let result = isSubstring(punctLess, string2, a, b);

if (result) {
  console.log("Yes");
} else {
  console.log("No");
}

修改后出错的代码

function isSubstring(string1, string2, a, b)
{
    if (a == 0)
        return true;
    if (b == 0)
        return false;

    if (string1[a - 1] == string2[b - 1])
        // 同样存在2-1的笔误
        return isSubstring(string1, string2,
                a - 1, 2 - 1);
    return isSubstring(string1, string2, a, b - 1);
}

const mp = new Map();
mp.set('string1', 'ello');
mp.set('string2', 'hello, friend!')

// 错误:用数组索引方式取Map的值
var punctLess = mp[0].replace(/[.,\/#!$%\^&*;:{}=\-_`~()]/g,"").replace(/\s{2,}/g," ");

// 错误:同样用数组索引取Map值
let a = mp[0].length;
let b = mp[1].length;
// 错误:引用未定义的string2变量
let result = isSubstring(punctLess, string2, a, b);

if (result){
    console.log("Yes");
} else {
    console.log("No");
}

错误点分析

  • Map取值方式错误:JavaScript的Map对象不能像数组那样通过索引(mp[0])访问元素,必须使用get(key)方法,比如获取string1的值要写mp.get('string1')。
  • 未定义变量引用:调用isSubstring时使用了string2,但代码里没有定义这个变量,应该替换为mp.get('string2')。
  • 递归参数笔误:两处递归调用中都把b-1写成了2-1,这会导致递归逻辑完全错误,必须修正为b-1。

修正后的代码

function isSubstring(string1, string2, a, b) {
    if (a === 0) return true;
    if (b === 0) return false;

    // 修正笔误:把2-1改为b-1
    if (string1[a - 1] === string2[b - 1]) {
        return isSubstring(string1, string2, a - 1, b - 1);
    }
    return isSubstring(string1, string2, a, b - 1);
}

// 正确初始化Map
const mp = new Map();
mp.set('string1', 'ello');
mp.set('string2', 'hello, friend!');

// 用get方法获取Map中的值
const targetStr = mp.get('string1');
var punctLess = targetStr
    .replace(/[.,\/#!$%\^&*;:{}=\-_`~()]/g, "")
    .replace(/\s{2,}/g, " ");

// 正确获取两个字符串的长度
let a = targetStr.length;
let b = mp.get('string2').length;
// 正确传入Map中存储的string2
let result = isSubstring(punctLess, mp.get('string2'), a, b);

if (result) {
    console.log("Yes");
} else {
    console.log("No");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:01:02