Object.is()

Object.is() 静态方法判断两个值是否为 相同的值

¥The Object.is() static method determines whether two values are the same value.

Try it

语法

¥Syntax

js
Object.is(value1, value2)

参数

¥Parameters

value1

要比较的第一个值。

value2

要比较的第二个值。

返回值

¥Return value

一个布尔值,指示两个参数是否为相同值。

¥A boolean indicating whether or not the two arguments are the same value.

描述

¥Description

Object.is() 确定两个值是否为 相同的值。如果满足以下条件之一,则两个值相同:

¥Object.is() determines whether two values are the same value. Two values are the same if one of the following holds:

  • 都是 undefined
  • 都是 null
  • 两者都是 true 或两者都是 false
  • 两个字符串具有相同的长度、相同的字符且顺序相同
  • 都是同一个对象(意味着两个值都引用内存中的同一个对象)
  • 两个 BigInts 具有相同的数值
  • 两个 symbols 引用相同的符号值
  • 两个数字和
    • 都是 +0
    • 都是 -0
    • 都是 NaN
    • 或者两者都非零,不是 NaN,并且具有相同的值

Object.is() 不等于 == 运算符。== 运算符在测试相等性之前对双方应用各种强制转换(如果它们不是同一类型)(导致 "" == false 成为 true 之类的行为),但 Object.is() 不会强制任一值。

¥Object.is() is not equivalent to the == operator. The == operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as "" == false being true), but Object.is() doesn't coerce either value.

Object.is() 也不等同于 === 运算符。Object.is()=== 之间的唯一区别在于它们对有符号零和 NaN 值的处理。=== 运算符(和 == 运算符)将数值 -0+0 视为相等,但将 NaN 视为彼此不相等。

¥Object.is() is also not equivalent to the === operator. The only difference between Object.is() and === is in their treatment of signed zeros and NaN values. The === operator (and the == operator) treats the number values -0 and +0 as equal, but treats NaN as not equal to each other.

示例

¥Examples

使用 Object.is()

¥Using Object.is()

js
// Case 1: Evaluation result is the same as using ===
Object.is(25, 25); // true
Object.is("foo", "foo"); // true
Object.is("foo", "bar"); // false
Object.is(null, null); // true
Object.is(undefined, undefined); // true
Object.is(window, window); // true
Object.is([], []); // false
const foo = { a: 1 };
const bar = { a: 1 };
const sameFoo = foo;
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(foo, sameFoo); // true

// Case 2: Signed zero
Object.is(0, -0); // false
Object.is(+0, -0); // false
Object.is(-0, -0); // true

// Case 3: NaN
Object.is(NaN, 0 / 0); // true
Object.is(NaN, Number.NaN); // true

规范

Specification
ECMAScript Language Specification
# sec-object.is

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看