JavaScript 中 null 如何轉換為布林值?
在 JavaScript 中,null 是一個預定義的關鍵字,表示空值或未知值(無值)。null 的資料型別是物件。在本文中,我們將學習如何使用多種方法將 null 轉換為布林值。
- 使用 Boolean 函式
- 使用 !! 運算子
使用 Boolean 函式
Boolean 函式用於獲取任何變數、條件或物件的布林值(true 或 false)。要將 null 轉換為布林值,只需將 null 傳遞給 Boolean 函式。
語法
Boolean(null)
示例 1
在這個例子中,我們建立了一個名為 bool 的變數,並將 null 傳遞到 Boolean 函式中,並將返回值儲存到 bool 中,然後列印結果。
<html> <head> <title> Example: Convert null to Boolean</title> </head> <body> <p> Convert null to Boolean using the Boolean() Method </p> <p id ="output"></p> <script> let bool = Boolean(null) document.getElementById("output").innerHTML += bool +"<br>"; document.getElementById("output").innerHTML += typeof bool </script> </body> </html>
示例 2
避免使用 new Boolean()
在下面的例子中,我們將演示為什麼不應該使用 new Boolean() 將 null 轉換為布林值。因為當我們使用 new Boolean() 時,它返回的是一個物件,而不是布林值。
<html> <head> <title> Example: Convert null to Boolean</title> </head> <body> <p> Convert null to Boolean using the Boolean() Method </p> <p id ="output"></p> <script> let bool = new Boolean(null) document.getElementById("output").innerHTML += bool +"<br>"; document.getElementById("output").innerHTML += typeof bool </script> </body> </html>
使用 !! 運算子
邏輯非運算子後跟另一個邏輯非運算子是一種簡單而優雅的方法,用於將 null 轉換為布林值。第一個邏輯運算子將值轉換為布林值,另一個邏輯運算子反轉第一個運算子返回的值。
語法
!!object
讓我們用一個例子將運算子分解成兩部分
示例 3
在這個例子中,我們建立了一個名為 x 的變數,並將 Tutorials point 儲存到其中,並建立了另一個名為 x1 的變數,其中我們儲存了 !x 的值,這裡的邏輯運算子將值轉換為布林值,另一個運算子 (x2) 反轉第一個運算子 (x1) 給出的結果。
<html> <body> <p> Convert string to Boolean using the !! Operator </p> <p id ="output"></p> <script> var x = "Tutorials Point" var x1 = !x; // false var x2 = !!x; // true document.write(x1 + " <br>") document.write(x2) </script> </body> </html>
示例 4
在這個例子中,我們將 null 轉換為布林值。
<html> <head> <title> Example: Convert null to Boolean</title> </head> <body> <p>Convert null to Boolean using the !! Operator</p> <p id ="output"></p> <script> let bool = !!null; document.getElementById("output").innerHTML += bool +"<br>"; document.getElementById("output").innerHTML += typeof bool </script> </body> </html>
正如我們提到的兩種方法一樣,效能都很好。Boolean 函式被一些開發者廣泛使用,而 !! 運算子方法看起來不太易讀,一些開發者不知道它。如果我們談論這兩種解決方案的速度,!! 運算子比 Boolean 函式略快。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP