JavaScript 中 null 如何轉換為字串?
在 JavaScript 中,null 是一個預定義的關鍵字,表示空值或未知值(無值)。null 的資料型別是物件。在本文中,我們將學習如何使用多種方法將 null 轉換為字串,如下所示。
- 使用 String() 方法
- 將 null 與空字串連線
- 使用邏輯或 (||)
- 使用三元運算子
使用 String() 方法
JavaScript 中的 String() 用於將值轉換為字串。要將 null 轉換為字串,只需將 null 傳遞給此方法即可。以下是使用此方法將 null 轉換為字串的示例。
語法
String( null )
示例 1
在下面的程式中,我們使用 String() 方法將 null 轉換為字串。我們還在轉換後檢查了型別。
<html> <head> <title> Example: Convert null to String</title> </head> <body> <p>Convert null to Number using the String() Method</p> <p id ="output"></p> <script> let str = null; str = String(str); document.getElementById("output").innerHTML += str +"<br>"; document.getElementById("output").innerHTML += typeof str </script> </body> </html>
示例 2
避免使用 new String()
在下面的程式中,我們演示了為什麼不應使用 new 與 String() 一起將 null 轉換為字串。new String() 建立一個物件而不是字串。
<html> <head> <title> Example: Convert null to String</title> </head> <body> <p>Convert null to Number using the String() Method</p> <p id ="output"></p> <script> let str = null; str = new String(str); document.getElementById("output").innerHTML += str +"<br>"; document.getElementById("output").innerHTML += typeof str </script> </body> </html>
請注意,使用 new String() 轉換後,變數 str 的型別是物件。
將 null 與空字串連線
如果我們將 null 與空字串 ("") 連線,結果將是字串型別。我們可以使用此技術將 null 轉換為字串。我們使用 + 運算子連線 null 和空字串 ("")。以下是使用此方法將 null 轉換為字串的示例。
語法
null + ""
示例
在下面的程式中,我們使用 + 將 null 與 "" 連線以將 null 轉換為字串。
<html> <head> <title> Example: Convert null to String</title> </head> <body> <p>Convert null to Number by concatenating null with empty string</p> <p id ="output"></p> <script> let str = null; str = str + "" document.getElementById("output").innerHTML += str +"<br>"; document.getElementById("output").innerHTML += typeof str </script> </body> </html>
使用邏輯或 (||)
或運算子在 JavaScript 中由 || 符號表示。要將 null 轉換為數字,我們使用或運算子與 null 和任何數字,或運算子將返回該數字。
語法
null || "null";
示例
在這個例子中,我們建立了一個名為 num 的變數,並將其值賦值為null || "null"。
<html> <html> <head> <title> Example: Convert null to String</title> </head> <body> <p>Convert null to Number using Logical OR (||)</p> <p id ="output"></p> <script> let str = null || " null "; document.getElementById("output").innerHTML += str +"<br>"; document.getElementById("output").innerHTML += typeof str </script> </body> </html>
使用三元運算子
條件運算子或三元運算子首先計算表示式的真假值,然後根據計算結果執行兩個給定語句中的一個。
語法
null ? null : "null"
示例
在給定的示例中,清楚地說明了如何使用三元運算子將 null 轉換為字串。
<html> <head> <title> Example: Convert null to String</title> </head> <body> <p>Convert null to Number using Ternary Operator</p> <p id ="output"></p> <script> let str = null ? null: " null "; document.getElementById("output").innerHTML += str +"<br>"; document.getElementById("output").innerHTML += typeof str </script> </body> </html>
廣告