在 JavaScript 型別轉換中,“+” 運算子的重要性是什麼?


Java script 是一種大部分時間自主執行的語言,操作直接將值轉換為其寫入型別。但是,也有一些情況我們需要進行顯式型別轉換。

雖然 Java script 提供了許多將資料從一種形式轉換為另一種形式的方法。但是,有兩種最常見的轉換型別。

  • 將值轉換為字串。

  • 將值轉換為數字。

隱式轉換

JavaScript 中有各種運算子和函式可以自動將值轉換為正確的型別,例如 JavaScript 中的 alert() 函式接受任何值並將其轉換為字串。但是,各種運算子會產生問題,例如“+”運算子。

Input "5" + "5" output : "55"
Here "+" operator stands for string concatenation in that case.

Input "5" - "2" output : "3"
Here output is 2 because Implict Conversion.

示例:1

以下示例演示了 JavaScript 中的隱式型別轉換。

<!DOCTYPE html>
<html>
<head>
   <title>type conversion</title>
</head>
<body>
   <script>
      document.write('("5" - "3") = ' + ("5" - "3") + "<br>");
      document.write('("5" - 3) = ' + ("5" - 3) + "<br>");
      document.write('("5" * "2") = ' + "5" * "2" + "<br>");
      document.write('("5" % "2") = ' + ("5" % "2") + "<br>");
      document.write('("5" + null) = ' + ("5" + null) + "<br>");
   </script>
</body>
</html>

注意− 在上述示例中,“+”運算子僅連線值,因為“+”運算子代表字串。

示例 2:將值轉換為字串

String()toString() 是 JavaScript 中的兩個函式,它們將值轉換為字串。

在以下示例中,我們將數字轉換為字串,布林值轉換為字串,以及日期轉換為字串。

<!DOCTYPE html>
<html>
<head>
   <title>type conversion</title>
</head>
<body>
   <script>
      // Number and date has been assigned
      // to variable A and B respectively
      var A = 155;
      var B = new Date("1995-12-17T03:24:00");
      
      // number to string
      document.write(" String(A) = " + String(A) + "<br>");
      
      // number to string
      document.write(" String(A + 11) = " + String(A + 11) + "<br>");
      document.write(" String( 10 + 10) = " + String(10 + 10) + "<br>");
      
      // boolean value to string
      document.write(" String(false) = " + String(false) + "<br>");
      
      // Date to string
      document.write(" String(B) = " + String(B) + "<br>");
   </script>
</body>
</html>

示例 3

在以下程式碼中,我們解釋了“+”運算子如何在不同型別的資料中工作。

如果我們在兩個數字之間使用“+”,它將直接將數字相加,並將輸出作為總數值。

如果我們在一個字串和一個數字之間使用“+”,它將連線數字,並將輸出作為字串值。

如果我們在兩個字串之間使用“+”,它將連線字串,並形成一個字串值。

<!DOCTYPE html>
<html>
<head>
   <title>type conversion</title>
</head>
<body>
   <script>
      document.write(5 + 5 + "<br/>");
      document.write( "One is a string and one is a number:" + "5" + 5 + "<br/>" );
      document.write( "One is a number and one is the string:" + 5 + "5" + "<br/>" );
      document.write(" Both are strings: " + "5" + "5" + "<br/>");
   </script>
</body>
</html>

更新於:2022-12-06

171 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.