逻辑非 (!)

逻辑 NOT (!)(逻辑补、否定)运算符将真变为假,反之亦然。它通常与布尔(逻辑)值一起使用。当与非布尔值一起使用时,如果其单个操作数可以转换为 true,则返回 false;否则,返回 true

¥The logical NOT (!) (logical complement, negation) operator takes truth to falsity and vice versa. It is typically used with boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true; otherwise, returns true.

Try it

语法

¥Syntax

js
!x

描述

¥Description

如果单个操作数可以转换为 true,则返回 false;否则,返回 true

¥Returns false if its single operand can be converted to true; otherwise, returns true.

如果一个值可以转换为 true,则该值就是所谓的 truthy。如果一个值可以转换为 false,则该值就是所谓的 falsy

¥If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.

可以转换为 false 的表达式示例有:

¥Examples of expressions that can be converted to false are:

  • null
  • NaN
  • 0
  • 空字符串(""'' 或 ````);
  • undefined

尽管 ! 运算符可以与不是布尔值的操作数一起使用,但它仍然可以被视为布尔运算符,因为它的返回值始终可以转换为 布尔原语。要将其返回值(或一般的任何表达式)显式转换为相应的布尔值,请使用双 NOT 运算符 (!!) 或 Boolean 构造函数。

¥Even though the ! operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator (!!) or the Boolean constructor.

示例

¥Examples

使用“非”

¥Using NOT

以下代码显示了 !(逻辑 NOT)运算符的示例。

¥The following code shows examples of the ! (logical NOT) operator.

js
!true; // !t returns false
!false; // !f returns true
!""; // !f returns true
!"Cat"; // !t returns false

双非 (!!)

¥Double NOT (!!)

可以串联使用几个 NOT 运算符来显式强制将任何值转换为相应的 布尔原语。转换基于值的 "truthyness" 或 "falsyness"(请参阅 truthyfalsy)。

¥It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the "truthyness" or "falsyness" of the value (see truthy and falsy).

可以通过 Boolean() 函数完成相同的转换。

¥The same conversion can be done through the Boolean() function.

js
!!true; // !!truthy returns true
!!{}; // !!truthy returns true: any object is truthy...
!!new Boolean(false); // ...even Boolean objects with a false .valueOf()!
!!false; // !!falsy returns false
!!""; // !!falsy returns false
!!Boolean(false); // !!falsy returns false

NOT 之间的转换

¥Converting between NOTs

以下涉及布尔值的运算:

¥The following operation involving booleans:

js
!!bCondition

总是等于:

¥is always equal to:

js
bCondition

规范

Specification
ECMAScript Language Specification
# sec-logical-not-operator

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also