JavaScript 布尔值

在 JavaScript 中,布尔值是基本数据类型,只能是 truefalse。例如,

const a = true;
const b = false;

注意:如果将 truefalse 放在引号中,它们将被视为字符串。

例如,

const a = 'true';
console.log(typeof a); // string

布尔值主要用于 比较和逻辑运算符。例如,

等于运算符 == 在操作数相等时返回 true

console.log(5 == 6); // false

不等于运算符 != 在所有操作数都不相等时返回 true

console.log(5 != 6); // true

逻辑与 && 在两个操作数的值都为 true 时返回 true,否则为 false

console.log(true && false); // false

布尔值也用于 if...else 语句和 for 循环。

以下是会被转换为特定布尔值的数值列表。

数据类型 布尔值
undefined false
null false
NaN false
'' false
0 false
20 true
-20 true
'hello' true

JavaScript 布尔方法

以下是 JavaScript 中内置布尔方法的列表。

方法 描述
toString() 通过将布尔值转换为字符串来返回布尔值
valueOf() 返回布尔值的原始值

示例:使用 toString()

let count = false;

// converting to string
let result = count.toString();

console.log(result);
console.log(typeof result);

输出

false
string

示例:使用 valueOf()

let count = true;

// converting to string
let result = count.valueOf();

console.log(result);

console.log(typeof result);

输出

true
boolean

JavaScript Boolean() 函数

Boolean() 函数用于将各种数据类型转换为布尔值。例如,

const a = true;
console.log(Boolean(a)); // true

所有有值的都会返回 true。例如,

let result;
result = 20;
console.log(Boolean(result)); // true
console.log(typeof Boolean(result)); // boolean

result = -20;
console.log(Boolean(result)); // true

result = 'hello';
console.log(Boolean(result)); // true

result = {a: 1};
console.log(Boolean(result)); // true

在 JavaScript 中,undefinednull0NaN'' 会转换为 false。例如,

let result;
// empty string
result = Boolean('');
console.log(result); // false

result = Boolean(0);
console.log(result); // false

result = Boolean(undefined);
console.log(result); // false

result = Boolean(null);
console.log(result); // false

result = Boolean(NaN);
console.log(result); // false

注意:如果您想了解更多关于布尔值转换的信息,请访问 JavaScript 类型转换


布尔对象

您也可以使用 new 关键字创建布尔值。例如,

const a = true;

// creating a boolean object
const b = new Boolean(true);

console.log(a); // true
console.log(b); // true

console.log(typeof a); // "boolean"
console.log(typeof b); // "object"

注意:建议避免使用布尔对象。使用布尔对象会减慢程序运行速度。

视频:JavaScript 布尔值

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战