在 TypeScript 中将布尔值转换为数字
Convert a Boolean to a Number in TypeScript
使用该Number
对象将布尔值转换为 TypeScript 中的数字,例如
const num = Number(true)
. 当用作函数时,Number(value)
将值转换为数字。如果无法转换该值,则返回NaN
(不是数字)。
const bool1 = true; // 👇️ const num1: number const num1 = Number(bool1); console.log(num1); // 👉️ 1 const bool2 = false; // 👇️ const num2: number const num2 = Number(bool2); console.log(num2); // 👉️ 0
我们使用
Number
函数将布尔值转换为数字。
true
值为get converted to1
和false
values get converted to的布尔值0
。
You might also see developers use the
unary plus (+)
operator to convert a boolean to a number.
const bool1 = true; // 👇️ const num1: number const num1 = +bool1; console.log(num1); // 👉️ 1 const bool2 = false; // 👇️ const num2: number const num2 = +bool2; console.log(num2); // 👉️ 0
It achieves the same goal as the Number
function, but might be confusing to
readers of your code who are not familiar with the unary plus (+) operator.
You should avoid using the unary plus (+) operator when adding numbers, because
it makes your code look quite strange.
const bool1 = true; const bool2 = false; const sum = +bool1 + +bool2; console.log(sum); // 👉️ 1
The second plus is the addition operator and the other ones are used to convert
the boolean values to numbers.
number
.Which approach you pick is a matter of personal preference. I’d go with using
the Number()
function as it’s more explicit and makes your code easier to
read.