JavaScript true 关键字
最后修改于 2025 年 4 月 16 日
在本文中,我们将展示如何在 JavaScript 中使用 true 布尔字面量。 true 关键字表示 JavaScript 中两种可能的布尔值之一。
true 关键字
true 关键字是 JavaScript 的布尔字面量之一,表示逻辑真值。 它是 JavaScript 中的原始值之一,与 false、数字、字符串等一起出现。
布尔值在编程中是做出决策和控制程序流程的基础。 true 值通常是比较操作或逻辑表达式的结果。
在 JavaScript 中,true 与真值并不相同。 虽然许多值可以在布尔上下文中被认为是真值,但 true 是表示真的显式布尔值。
基本 true 值
使用 true 的最简单方法是作为直接的布尔值。
let isActive = true;
if (isActive) {
console.log("The feature is active");
} else {
console.log("The feature is inactive");
}
在这里,我们为变量赋值 true,并在条件语句中使用它。 当条件评估为 true 时,if 语句会执行其代码块。 这演示了基本的布尔变量用法。
$ node main.js The feature is active
比较返回 true
比较操作通常会产生 true 或 false。
let x = 10;
let y = 5;
let result = x > y;
console.log(result);
if (x > y) {
console.log("x is greater than y");
}
比较 x > y 的结果为 true,因为 10 大于 5。 我们将此结果存储在一个变量中,并将其直接用于 if 语句中。 这表明比较如何生成布尔值。
$ node main.js true x is greater than y
逻辑 AND 运算符
当两个操作数都为真值时,逻辑 AND 运算符 (&&) 返回 true。
let hasPermission = true;
let isLoggedIn = true;
let canAccess = hasPermission && isLoggedIn;
console.log(canAccess);
if (hasPermission && isLoggedIn) {
console.log("Access granted");
}
当两个变量都为 true 时,AND 操作返回 true。 这对于检查所有都必须为真的多个条件非常有用。 结果被存储并直接用于条件中。
$ node main.js true Access granted
逻辑 OR 运算符
如果至少一个操作数为真值,则逻辑 OR 运算符 (||) 返回 true。
let isAdmin = false;
let isModerator = true;
let hasPrivileges = isAdmin || isModerator;
console.log(hasPrivileges);
if (isAdmin || isModerator) {
console.log("User has privileges");
}
OR 运算符返回 true,因为其中一个操作数为 true。 这演示了如何检查是否至少满足一个条件。 当找到第一个真值时,操作会短路。
$ node main.js true User has privileges
布尔函数
Boolean() 函数可以将值转换为其布尔表示形式。
let value1 = Boolean(1);
let value2 = Boolean("hello");
let value3 = Boolean(true);
console.log(value1);
console.log(value2);
console.log(value3);
Boolean() 函数将真值转换为 true。 非零数字、非空字符串和 true 本身都会转换为 true。 这显示了显式布尔转换。
$ node main.js true true true
真值 vs true
区分真值和 true 布尔值很重要。
let value = "hello";
if (value) {
console.log("The string is truthy");
}
if (value === true) {
console.log("The string equals true");
} else {
console.log("The string doesn't equal true");
}
虽然字符串是真值(导致第一个 if 执行),但它不等于布尔值 true。 这演示了真值和实际的 true 布尔字面量之间的区别。
$ node main.js The string is truthy The string doesn't equal true
默认函数参数
true 值可以用作函数中的默认参数。
function greet(name, verbose = true) {
if (verbose) {
console.log(`Hello, ${name}! Welcome to our application.`);
} else {
console.log(`Hello, ${name}`);
}
}
greet("John");
greet("Alice", false);
在这里,我们将 true 用作 verbose 参数的默认值。 当未指定时,verbose 默认为 true,显示完整的问候语。 当设置为 false 时,将显示一个较短的版本。
$ node main.js Hello, John! Welcome to our application. Hello, Alice
来源
在本文中,我们已经演示了如何在 JavaScript 编程中使用 true 布尔字面量。