3 回答
TA贡献1872条经验 获得超3个赞
我可以看到三种解决方法:
使用模板字符串,就像设计使用的那样,没有任何format功能:
console.log(`Hello, ${"world"}. This is a ${"test"}`);
// might make more sense with variables:
var p0 = "world", p1 = "test";
console.log(`Hello, ${p0}. This is a ${p1}`);
// or even function parameters for actual deferral of the evaluation:
const welcome = (p0, p1) => `Hello, ${p0}. This is a ${p1}`;
console.log(welcome("world", "test"));
不要使用模板字符串,而应使用纯文本字符串:
String.prototype.format = function() {
var args = arguments;
return this.replace(/\$\{p(\d)\}/g, function(match, id) {
return args[id];
});
};
console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));
使用带标签的模板文字。请注意,替换仍将在不被处理程序拦截的情况下进行求值,因此您不能像p0没有变量so 那样使用标识符。如果接受其他替换主体语法建议,此行为可能会更改(更新:否)。
function formatter(literals, ...substitutions) {
return {
format: function() {
var out = [];
for(var i=0, k=0; i < literals.length; i++) {
out[k++] = literals[i];
out[k++] = arguments[substitutions[i]];
}
out[k] = literals[i];
return out.join("");
}
};
}
console.log(formatter`Hello, ${0}. This is a ${1}`.format("world", "test"));
// Notice the number literals: ^ ^
TA贡献1111条经验 获得超0个赞
AFAIS,有用的功能“延迟执行字符串模板”仍然不可用。但是,使用lambda是一种表达力强,易读且简短的解决方案:
var greetingTmpl = (...p)=>`Hello, ${p[0]}. This is a ${p[1]}`;
console.log( greetingTmpl("world","test") );
console.log( greetingTmpl("@CodingIntrigue","try") );
添加回答
举报