在 JavaScript 中,template strings 可以在字串裡嵌入運算式,這種做法也稱為字串插值。這項功能擴充了內建的 String 全域物件所提供的功能。
你可以把文字用反引號包起來,在 JavaScript 中建立 template strings。它不僅能讓文字包含換行和其他特殊字元,還可以嵌入變數和其他運算式。
const num1 = 1;
const num2 = 2;
`Adding ${num1} and ${num2} gives ${num1 + num2}.`;
// => Adding 1 and 2 gives 3.
在上面的例子中,反引號(``)用來表示 template strings。其中${...}是用來代入內容的佔位符。任何非字串型別都會_隱式_轉換成字串,這個主題會在型別轉換概念中介紹。所有型別的運算式都可以用在 template strings 裡。
const track = 'JavaScript';
`This track on exercism.org is ${track.toUpperCase()}.`;
// => This track on exercism.org is JAVASCRIPT.
當你需要把字串排成好幾行時:
`This is an example of using template
strings to accomplish multiple
lines`;
有了這些代入功能,你還可以在流程中加入邏輯,決定輸出的字串應該是什麼。處理這些邏輯的其中一種做法,是使用三元運算子,它用稍微不同的格式,提供和if/else一樣的條件功能。
要在 template strings 語法中加入邏輯:
const grade = 95;
`You have ${grade > 90 ? 'passed' : 'failed'} the exam.`;
// => You have passed the exam.