布尔值

Boolean 值可以是以下两个值之一:truefalse,代表逻辑命题的真值。

¥**Boolean** values can be one of two values: true or false, representing the truth value of a logical proposition.

描述

¥Description

布尔值通常由 关系运算符相等运算符逻辑 NOT (!) 产生。它们也可以由表示条件的函数生成,例如 Array.isArray()。请注意,二进制逻辑运算符(例如 &&||)返回操作数的值,这些值可能是也可能不是布尔值。

¥Boolean values are typically produced by relational operators, equality operators, and logical NOT (!). They can also be produced by functions that represent conditions, such as Array.isArray(). Note that binary logical operators such as && and || return the values of the operands, which may or may not be boolean values.

布尔值通常用于条件测试,例如 if...elsewhile 语句的条件、条件运算符? :)或 Array.prototype.filter() 的谓词返回值。

¥Boolean values are typically used in conditional testing, such as the condition for if...else and while statements, the conditional operator (? :), or the predicate return value of Array.prototype.filter().

你很少需要明确将某些内容转换为布尔值,因为 JavaScript 会在布尔上下文中自动执行此操作,因此你可以根据其 truthiness 将任何值用作布尔值。我们还鼓励你在自己的代码中使用 if (condition)if (!condition) 而不是 if (condition === true)if (condition === false),以便你可以利用此约定。但是,确保表示条件的值始终是布尔值可以帮助阐明代码的意图。

¥You would rarely need to explicitly convert something to a boolean value, as JavaScript does this automatically in boolean contexts, so you can use any value as if it's a boolean, based on its truthiness. You are also encouraged to use if (condition) and if (!condition) instead of if (condition === true) or if (condition === false) in your own code so you can take advantage of this convention. However, making sure that values representing conditions are always booleans can help clarify the intent of your code.

js
// Do this:
// This always returns a boolean value
const isObject = (obj) => !!obj && typeof obj === "object";

// Or this:
const isObject = (obj) => Boolean(obj) && typeof obj === "object";

// Or this:
const isObject = (obj) => obj !== null && typeof obj === "object";

// Instead of this:
// This may return falsy values that are not equal to false
const isObject = (obj) => obj && typeof obj === "object";

布尔基元和布尔对象

¥Boolean primitives and Boolean objects

要将非布尔值转换为布尔值,请使用 Boolean 作为函数或使用 双非 运算符。不要将 Boolean() 构造函数与 new 一起使用。

¥For converting non-boolean values to boolean, use Boolean as a function or use the double NOT operator. Do not use the Boolean() constructor with new.

js
const good = Boolean(expression);
const good2 = !!expression;
js
const bad = new Boolean(expression); // don't use this!

这是因为所有对象(包括封装值为 falseBoolean 对象)都是 truthy,并且在条件语句等位置评估为 true。(另请参阅下面的 布尔强制 部分。)

¥This is because all objects, including a Boolean object whose wrapped value is false, are truthy and evaluate to true in places such as conditional statements. (See also the boolean coercion section below.)

js
if (new Boolean(true)) {
  console.log("This log is printed.");
}

if (new Boolean(false)) {
  console.log("This log is ALSO printed.");
}

const myFalse = new Boolean(false); // myFalse is a Boolean object (not the primitive value false)
const g = Boolean(myFalse); // g is true
const myString = new String("Hello"); // myString is a String object
const s = Boolean(myString); // s is true

警告:你应该很少发现自己使用 Boolean 作为构造函数。

¥Warning: You should rarely find yourself using Boolean as a constructor.

布尔强制

¥Boolean coercion

许多期望布尔值的内置操作首先将其参数强制为布尔值。操作 可概括如下:

¥Many built-in operations that expect booleans first coerce their arguments to booleans. The operation can be summarized as follows:

  • 布尔值按原样返回。
  • undefined 变成 false
  • null 变成 false
  • 0-0NaN 变成 false;其他数字变成 true
  • 0n 变成 false;其他 BigInts 变成 true
  • 空字符串 "" 变成 false;其他字符串变成 true
  • 符号 变成 true
  • 所有对象都变成 true

注意:遗留行为使得 document.all 在用作布尔值时返回 false,尽管它是一个对象。此属性是遗留的且非标准的,不应使用。

¥Note: A legacy behavior makes document.all return false when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used.

注意:与 字符串强制数字强制 等其他类型转换不同,布尔强制不会尝试通过调用用户方法来 将对象转换为原语

¥Note: Unlike other type conversions like string coercion or number coercion, boolean coercion does not attempt to convert objects to primitives by calling user methods.

换句话说,只有少数值被强制为 false - 这些值称为 falsy 值。所有其他值称为 truthy 值。当与逻辑运算符、条件语句或任何布尔上下文一起使用时,值的真实性非常重要。

¥In other words, there are only a handful of values that get coerced to false — these are called falsy values. All other values are called truthy values. A value's truthiness is important when used with logical operators, conditional statements, or any boolean context.

在 JavaScript 中有两种方法可以达到相同的效果。

¥There are two ways to achieve the same effect in JavaScript.

  • 双非!!xx 取反两次,这使用与上面相同的算法将 x 转换为布尔值。
  • Boolean() 功能:Boolean(x) 使用与上面相同的算法来转换 x

请注意,真实性与 松散平等truefalse 不同。

¥Note that truthiness is not the same as being loosely equal to true or false.

js
if ([]) {
  console.log("[] is truthy");
}
if ([] == false) {
  console.log("[] == false");
}
// [] is truthy
// [] == false

[] 是真实的,但它也大致等于 false。它是真实的,因为所有对象都是真实的。然而,当与作为基元的 false 进行比较时,[] 也被转换为基元,即通过 Array.prototype.toString() 变为 ""。比较字符串和布尔值,结果都是 转换为数字,并且它们都变成 0,因此 [] == falsetrue。一般来说,虚假性和 == false 在以下情况下有所不同:

¥[] is truthy, but it's also loosely equal to false. It's truthy, because all objects are truthy. However, when comparing with false, which is a primitive, [] is also converted to a primitive, which is "" via Array.prototype.toString(). Comparing strings and booleans results in both being converted to numbers, and they both become 0, so [] == false is true. In general, falsiness and == false differ in the following cases:

  • NaNundefinednull 是假的,但不松散地等于 false
  • "0"(以及不是 "" 而是 被强制为 0 的其他字符串文字)是真实的,但大致等于 false
  • 对象总是真实的,但它们的原始表示可能大致等于 false

真值更不可能松散地等于 true。所有值要么为真,要么为假,但大多数值都不大致等于 truefalse

¥Truthy values are even more unlikely to be loosely equal to true. All values are either truthy or falsy, but most values are loosely equal to neither true nor false.

构造函数

¥Constructor

Boolean()

创建 Boolean 对象。当作为函数调用时,它返回布尔类型的原始值。

实例属性

¥Instance properties

这些属性在 Boolean.prototype 上定义并由所有 Boolean 实例共享。

¥These properties are defined on Boolean.prototype and shared by all Boolean instances.

Boolean.prototype.constructor

创建实例对象的构造函数。对于 Boolean 实例,初始值为 Boolean 构造函数。

实例方法

¥Instance methods

Boolean.prototype.toString()

根据对象的值返回 truefalse 的字符串。覆盖 Object.prototype.toString() 方法。

Boolean.prototype.valueOf()

返回 Boolean 对象的原始值。覆盖 Object.prototype.valueOf() 方法。

示例

¥Examples

创建假值

¥Creating false values

js
const bNoParam = Boolean();
const bZero = Boolean(0);
const bNull = Boolean(null);
const bEmptyString = Boolean("");
const bfalse = Boolean(false);

创建真值

¥Creating true values

js
const btrue = Boolean(true);
const btrueString = Boolean("true");
const bfalseString = Boolean("false");
const bSuLin = Boolean("Su Lin");
const bArrayProto = Boolean([]);
const bObjProto = Boolean({});

规范

Specification
ECMAScript Language Specification
# sec-boolean-objects

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also