JavaScript - 模板字面量



JavaScript 模板字面量

在 JavaScript 中,模板字面量是在 ES6 中引入的,用於動態自定義字串。模板字面量允許您將變數或表示式新增到字串中,並且字串會根據變數和表示式的值變化而變化。

模板字面量有多個同義詞。例如,模板字串、字串模板、反引號語法等。

語法

請遵循以下語法在 JavaScript 中使用模板字面量。

let str = `Hi ${name}`;

您需要在反引號 (``) 之間編寫字串。要將動態變數或表示式與字串一起使用,需要將其放在 ${} 之間。

此外,使用模板字面量,您不需要跳脫字元來在字串中新增單引號或雙引號。

示例

示例:使用模板字面量建立字串

在下面的示例中,我們使用模板字面量建立了一個包含特殊字元的字串。

str1 字串與我們使用單引號或雙引號建立的常規字串相同。str2 字串包含帶有字串的單引號。在這裡,您可以看到我們沒有使用跳脫字元在字串中新增單引號。

<html>
<body>
   <div id = "output1"> </div>
   <div id = "output2"> </div>
   <script>
      let str1 = `Hello Users!`;
      let str2 = `'Tutorialspoint' is a good website`;
      document.getElementById("output1").innerHTML = str1;
      document.getElementById("output2").innerHTML = str2;
   </script>
</body>
</html>

輸出

Hello Users!
'Tutorialspoint' is a good website

示例:帶模板字面量的變數

以下程式碼演示瞭如何透過將變數傳遞到模板字面量字串中,在字串中使用動態值。

在這裡,我們定義了與汽車相關的變數。之後,我們使用模板字面量建立一個字串並新增變數。

在輸出中,您可以看到變數已在字串中替換為其值。

<html>
<body>
   <p id = "output"> </p>
   <script>
      let car = "BMW";
      let model = "X5";
      const price = 5000000;
      const carStr = `The price of the ${car} ${model} is ${price}.`;
      document.getElementById("output").innerHTML = carStr;
   </script>
</body>
</html>

輸出

The price of the BMW X5 is 5000000.

示例:帶模板字面量的表示式

您還可以使用模板字面量將表示式新增到字串中。

在 str1 字串中,我們添加了表示式以在模板字面量字串中執行兩個數字的求和。

在 str2 中,我們將函式呼叫作為表示式呼叫。它將表示式替換為函式返回的值。

<html>
<body>
   <div id = "output1"> </div>
   <div id = "output2"> </div>
   <script>
      function func() {
         return 10;
      }
       
      const str1 = `The sum of 2 and 3 is ${2 + 3}.`;
      const str2 = `The return value from the function is ${func()}`;
      
      document.getElementById("output1").innerHTML = str1;
      document.getElementById("output2").innerHTML = str2;
   </script>
</body>
</html>

輸出

The sum of 2 and 3 is 5.
The return value from the function is 10

JavaScript 巢狀模板字面量

JavaScript 允許您在其他模板字面量內部使用模板字面量,這稱為巢狀模板字面量。

示例

在下面的示例中,我們在外部模板字面量中添加了表示式。該表示式包含三元運算子。它檢查 2 是否小於 3。根據返回的布林值,它執行第一個或第二個巢狀表示式並列印結果。

<html>
<head>
   <title>Nested Template Literals</title>
</head>
<body>
   <p id = "output"> </p>
   <script>
      const nested = `The subtraction result is: ${2 < 3 ? `${3 - 2}` : `${2 - 3}`}`;
      document.getElementById("output").innerHTML = nested;
</script>
</body>
</html>

輸出

The subtraction result is: 1

示例:使用模板字面量建立多行字串

您也可以使用模板字面量來定義多行字串。

<html>
<body>
   <div id = "output"> </div>
   <script>
      function func() {
         return 10;
      }
      
      const str1 = `The sum of 2 and 3 is ${2 + 3}. <br>
      The return value from the function is ${func()}`;
      
      document.getElementById("output").innerHTML = str1;
   </script>
</body>
</html>

輸出

The sum of 2 and 3 is 5.
The return value from the function is 10
廣告