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

JS带占位符普通字符串转模板字符串插值对象数组变量不生效排查

问题原因

你的代码核心存在两处错误:

  • 路径解析逻辑无法识别可选链语法?.和数组索引方括号[]:你拿到的路径字符串是person?.[0]?.name,直接按.分割后得到的键为person?、[0]?、name,这些键在你的数据对象中不存在,所以每次取值都会触发兜底逻辑,返回原始占位符。
  • getObjPath的reduce遍历逻辑有缺陷:用||判断值是否存在,会把0、空字符串等合法假值也判定为不存在,直接返回兜底结果,且路径遍历过程中没有提前终止无效取值。

修复方案

首先要对路径字符串做格式化处理,把可选链符号、数组方括号统一转换成标准的点分隔路径,再调整取值逻辑的判断规则即可:

const getObjPath = (path, obj, fallback = `$\{${path}}`) => {
    if (!path || !obj) return fallback;
    // 格式化路径:把?.、[]都替换成.,清除多余问号,再过滤空项
    const keys = path.replace(/\?\./g, '.')
                    .replace(/\[(\d+)\]/g, '.$1')
                    .replace(/\?/g, '')
                    .split('.')
                    .filter(Boolean);
    return keys.reduce((res, key) => {
        // 仅当值为undefined/null时返回兜底,避免合法假值被误判
        if (res === undefined || res === null) return fallback;
        return res[key] ?? fallback;
    }, obj);
};

const interpolate = (template, variables, fallback) => {
    const regex = /\${[^{]+}/g;
    if (!template || !variables) return template;
    return template.replace(regex, (match) => {
        const [path, defaultVal] = match.slice(2, -1).trim().split('|').map(item => item.trim());
        return getObjPath(path, variables, defaultVal ?? fallback ?? match);
    });
};

const data = { person: [{ name: 'John', age: 18 }] };
// 调整模板去掉不需要的括号即可匹配预期输出
const a = interpolate('Hi ${person?.[0]?.name | text} ${person?.[0]?.age | text}', data);
console.log(a); // 输出:Hi John 18

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:09:03