您好,欢迎访问一九零五行业门户网

如何在JavaScript中将布尔值转换为数字?

在本教程中,我们将在 javascript 中将布尔值转换为数字。 boolean 是变量的数据类型,与其他编程语言一样,javascript 也支持该类型。
boolean 数据类型仅包含两个值,true 和 false。 在某些情况下,程序员必须将 true 或 false 值转换为号码。例如,使用严格相等运算符将布尔值与数字变量进行比较。
这里,使用不同的运算符,我们有三种方法将布尔值转换为数字。
使用 number() 函数在 javascript 中,number() 函数可用于将任何变量转换为数字。我们还可以使用它将布尔变量转换为数字。
语法用户可以按照以下语法将布尔值转换为数字。
let bool = true;let result = number(bool);
参数bool - 这是一个布尔变量,我们需要将其转换为数字。
示例在下面的示例中,我们使用 javascript 数字库的 number() 函数将 true 和 false 两个布尔值转换为数字。 number()函数返回 1 表示真值,0 表示假值。
<html><head></head><body> <h2>convert the boolean to number in javascript.</h2> <h4>convert the boolean ( true / false ) respectively to number using <i> number() </i> function.</h4> <div id=number1></div> <div id = number2></div></body><script> var number1 = document.getelementbyid(number1); var number2 = document.getelementbyid(number2); let bool = true; let result = number(bool); number1.innerhtml = result; number2.innerhtml = number(false);</script></html>
使用位运算符在本节中,我们将学习使用按位 or 和按位 and 运算符将布尔值转换为数字。当我们将布尔值与0进行按位或运算时,它返回数字值。
此外,当用户对 1 与任意布尔值进行按位与运算时,它会返回一个受尊重的数字值。
语法用户可以按照以下语法使用位运算符将布尔值转换为数字。
let bool = true;let result = bool | 0; // using the bitwise or operatorlet result = bool & 1; // using the bitwise and operator
示例在下面的示例中,我们采用了两个将布尔值转换为数字的不同示例,一个是使用按位|运算符,另一个使用按位&运算符。
<html><head></head><body> <h2>convert the boolean to number in javascript.</h2> <h4>converting the boolean true to number using <i> bitwise | </i> operator.</h4> <div id = number1></div> <h4>converting the boolean false to number using <i> bitwise &</i> operator.</h4> <div id = number2></div></body><script> var number1 = document.getelementbyid(number1); var number2 = document.getelementbyid(number2); let bool = true; let result = bool | 0; number1.innerhtml = result; bool = false; number2.innerhtml = bool & 1;</script></html>
使用算术运算符这是本教程将布尔值转换为数字的最后一种方法。我们将使用加法、乘法、算术运算符。但是,我们也可以使用减法和除法运算符。
当我们从布尔值中添加或减去 0 时,它会返回与布尔值相关的数字值。同样,当我们将布尔值乘以 1 时,它返回的结果与加法相同。
语法请按照以下语法使用乘法和加法运算符。
let bool = true;let result = bool + 0; // using the arithmetic + operatorlet result = bool * 1; // using the arithmetic * operator
示例在下面的示例中,我们使用加法和乘法运算符将布尔值转换为数字。
<html><head></head><body> <h2>convert the boolean to number in javascript.</h2> <h4>convert the boolean false to number using <i> arithmetic + </i> operator.</h4> <div id = number1></div> <h4>convert the boolean true to number using <i> arithmetic * </i> operator.</h4> <div id = number2></div></body><script> var number1 = document.getelementbyid(number1); var number2 = document.getelementbyid(number2); let bool = false; let result = bool + 0; number1.innerhtml = result; bool = true; number2.innerhtml = bool * 1;</script></html>
用户可以使用三种方法中的任何一种将布尔值转换为整数。第一种方法调用内置库函数,比第二种和第三种方法慢。在任何编程语言中,按位运算是最快的运算。所以,第二种方法是最快的方法,用户也可以轻松使用。
以上就是如何在javascript中将布尔值转换为数字?的详细内容。
其它类似信息

推荐信息