这就是我想要实现的目标。
let something = 'first string';
let template = `asdf=${something}asdf`;
some.method(template)
.then(function() {
let something = 'new string';
console.log(template);
// does not return 'asdf=new stringasdf' like expected
});
如何保留模板,但在需要时(在作用域函数内)切换其中的变量?
最佳答案
该模板基本上是以下内容的简写:
let template = "asdf=" + something + "asdf";
因此它在模板本身出现在代码中的位置进行评估。
我想你会想使用一个函数:
let template = function(something) { return `asdf=${something}asdf`; }
然后你可以这样做:
some.method(template(something)).then(function() { let something = 'new string'; console.log(template(something)); });
关于javascript - 如何替换 Javascript 模板字符串中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37915574/