3 回答

TA貢獻1872條經(jīng)驗 獲得超4個贊
我可以看到三種解決方法:
使用模板字符串,就像設計使用的那樣,沒有任何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條經(jīng)驗 獲得超0個贊
AFAIS,有用的功能“延遲執(zhí)行字符串模板”仍然不可用。但是,使用lambda是一種表達力強,易讀且簡短的解決方案:
var greetingTmpl = (...p)=>`Hello, ${p[0]}. This is a ${p[1]}`;
console.log( greetingTmpl("world","test") );
console.log( greetingTmpl("@CodingIntrigue","try") );
添加回答
舉報