JavaScript 中 null 如何轉換為布林值?


在 JavaScript 中,null 是一個預定義的關鍵字,表示空值或未知值,沒有值。null 的資料型別是物件。在本文中,我們將學習如何使用多種方法將 null 轉換為布林值,這些方法如下。

  • 使用 Boolean 函式
  • 使用 !! 運算子

使用 Boolean 函式

Boolean 函式用於獲取任何變數、條件或物件的布林值(truefalse)。要將 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 函式稍快。

更新於: 2022年8月11日

6K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.