判斷是否為布爾值的方法

判斷是否為布爾值的方法

Boolean() 構造函數可用于創建布爾對象以及布爾原始值,表示 true 或 false 值。

在下面的代碼中,我詳細介紹了 JavaScript 中布爾值的創建。

示例:sample52.html

 <script>  	// Create a Boolean Object using the new keyword and the Boolean() constructor. 	var myBoolean1 = new Boolean(false); // Using new keyword. 	console.log(typeof myBoolean1); // Logs 'object'.  	// Create a Boolean literal/primitive by directly using the number constructor without new. 	var myBoolean2 = Boolean(0); // Without new keyword. 	console.log(typeof myBoolean2); // Logs 'boolean'.  	// Create Boolean literal/primitive (constructor leveraged behind the scenes). 	var myBoolean3 = false; 	console.log(typeof myBoolean3); // Logs 'boolean'. 	console.log(myBoolean1, myBoolean2, myBoolean3); // Logs false false false.  </script>

Boolean() 參數

Boolean() 構造函數將一個參數轉換為布爾值(即 true 或 false)。任何非 0、-0、NULL、false、NaN、undefined 或空字符串 (“”) 的有效 JavaScript 值都將轉換為 true。在以下示例中,我們創建兩個布爾對象值:一個 true 和一個 false。

示例:sample53.html

 <script>  	// Parameter passed to Boolean() = 0 = false, thus foo = false 	var foo = new Boolean(0) 	console.log(foo);  	// Parameter passed to Boolean() = Math = true, thus bar = true 	var bar = new Boolean(Math) 	console.log(bar);  </script>

當與 new 關鍵字一起使用時,來自 Boolean() 構造函數的實例會生成一個實際的復雜對象。您應該避免使用 Boolean() 構造函數創建布爾值(而是使用文字/原始數字),因為存在與 typeof 運算符相關的潛在問題。 typeof 運算符將布爾對象報告為“object”,而不是您可能期望的原始標簽(“boolean”)。此外,文字/原始值的寫入速度更快。


Boolean() 屬性和方法

Boolean() 對象具有以下屬性:

屬性(例如,Boolean.prototype;):

  • 原型

布爾對象實例屬性和方法

布爾對象實例具有以下屬性和方法(不包括繼承的屬性和方法):

實例屬性(例如,var myBoolean = false; myBoolean.constructor;):

  • 構造函數

實例方法(例如,var myNumber = false; myBoolean.toString();):

  • toSource()
  • toString()
  • valueOf()

非原始 False 布爾對象轉換為 True

從 Boolean() 構造函數創建的 false 布爾對象(而不是原始值)是一個對象,并且對象會轉換為 true。因此,當通過 Boolean() 構造函數創建 false 布爾對象時,該值本身會轉換為 true。在下面的示例中,我演示了 false 布爾對象如何始終是“true”。

示例:sample54.html

 <script>  	var falseValue = new Boolean(false);  	console.log(falseValue); // We have a false Boolean object, but objects are truthy.  	if (falseValue) { // Boolean objects, even false Boolean objects, are truthy. 		console.log('falseValue is truthy'); 	}  </script>

如果需要將非布爾值轉換為布爾值,只需使用 Boolean() 構造函數,而不使用 new 關鍵字,返回的值將是原始值而不是布爾對象。 p>


某些事情是假的,其他一切都是真的

已經提到過,但值得再次提及,因為它與轉換有關:如果值為 0、-0、null、false、NaN、undefined,或空字符串( “”),就是false。如果在布爾上下文中使用,除上述值之外的 JavaScript 中的任何值都將轉換為 true(即 if (true) {};)。

示例:sample55.html

 <script>  	// All of these return a false Boolean value. 	console.log(Boolean(0)); 	console.log(Boolean(-0)); 	console.log(Boolean(null)); 	console.log(Boolean(false)); 	console.log(Boolean('')); 	console.log(Boolean(undefined)); 	console.log(Boolean(null));  	// All of these return a true Boolean value. 	console.log(Boolean(1789)); 	console.log(Boolean('false')); // 'false' as a string is not false the Boolean value. 	console.log(Boolean(Math)); 	console.log(Boolean(Array()));  </script>

結論

了解哪些 JavaScript 值被簡化為 false 至關重要,這樣您就知道所有其他值都被視為 true。

? 版權聲明
THE END
喜歡就支持一下吧
點贊13 分享