gpt4 book ai didi

javascript - map 函数后可能的 reducer 情况。

转载 作者:行者123 更新时间:2023-11-29 18:46:07 24 4
gpt4 key购买 nike

我正在尝试查看 array.reduce 在这种情况下是否是更好的选择。我想返回字符串结果,而不必在 forEach 循环中设置变量。

所以我正在做的是查看字符串中是否有匹配我的正则表达式的匹配项。然后获取该匹配项中的文本并将其替换为我传递给它的变量。一切都很好,但如果可以的话,我想清理它。 findReplaceTemplateString 是一个单独的函数,我同意。它的 forEach 感觉就像我可以使用 reducer 来返回完整的字符串。但我是 reducer 的新手,不确定这是否适合它。任何人对此有任何想法。

  const reg = /\{.+?\}/g;
const matches = tpl.match(reg);

let str = '';
matches.map(item => item.slice(1, -1)).forEach((placeHolder) => {
str = findReplace(tpl, placeHolder, props[placeHolder] || '');
});

最佳答案

我看不出让它过于复杂的意义所在。只需使用 String.prototype.replace()具有作为第二个参数的功能。这将使用有效参数动态替换您的模式。

const input = 'Hi there, {name}! What are you doing in {city}?';
const props = {name: 'Alex', city: 'St Petersburg'};

const output = input.replace(/\{.+?\}/g, (p) => {
return props[p.slice(1, -1)] || p /* here you may use '' */;
});

console.log( output );

关于javascript - map 函数后可能的 reducer 情况。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com