← 中文资源

简体中文版本

Object.is 区分 -0 与 0 和 NaN

Object.is 在 === 与预期不一致的两处给出正确身份:NaN 等于自身、-0 不等于 0;用 1/-0 得到 -Infinity 察觉 -0,Math.sign(-0) 也返回 -0,常规值上两者行为一致。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

-0 === 0: true
Object.is(-0, 0): false
NaN === NaN: false
Object.is(NaN, NaN): true
1 / -0: -Infinity
sign(-0) is -0: true
sign(-0) === 0: true
same: true false

实现说明

演示用的数据放在这几个模块级绑定中:negative。

使用要点

  • 直接运行文件,输出会带上标签,比如 -0 === 0:、Object.is(-0, 0):、NaN === NaN:——输出的每一行都能指回产生它的那次调用。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 文件的状态由几个模块级绑定持有:negative。

核心语句

const negative = -0;

代码示例

// === treats -0 and 0 as the same value; Object.is can tell them apart
console.log('-0 === 0:', -0 === 0);
console.log('Object.is(-0, 0):', Object.is(-0, 0));

// NaN is === false against everything, including itself; Object.is treats NaN as equal to itself
console.log('NaN === NaN:', NaN === NaN);
console.log('Object.is(NaN, NaN):', Object.is(NaN, NaN));

// 1 / -0 evaluates to -Infinity, one way to detect -0
const negative = -0;
console.log('1 / -0:', 1 / negative);

// Math.sign(-0) returns -0: === cannot tell them apart, Object.is can
console.log('sign(-0) is -0:', Object.is(Math.sign(-0), -0));
console.log('sign(-0) === 0:', Math.sign(-0) === 0);

// on ordinary values Object.is behaves exactly like ===
console.log('same:', Object.is('a', 'a'), Object.is(1, '1'));