JavaScript 相等判断怎么选:Object.is、=== 与 SameValueZero

10-21 6阅读

数组里明明有 NaN,为什么 indexOf 仍返回 -1,而 includes 却返回 true?把 -0 和 +0 放进 Set 为什么只剩一个元素,Object.is 又为什么说它们不同?这些现象来自不同的相等规则。理解规则,比把某个 API 记成“更严格”更有用。

本文用一份可直接运行的 Node.js 脚本验证 12 组场景。比较范围是 JavaScript 值与对象身份,不实现通用深比较,也不根据微型示例推断性能。

JavaScript 相等判断怎么选:Object.is、=== 与 SameValueZero

配图为独立模型生成的概念示意图,并非浏览器截图或内存布局图;图中对象方块仅用来提示对象身份与结构内容的区别。

一、先看两种特殊数值

比较对象===Object.isSameValueZero
NaN 与 NaNfalsetruetrue
+0 与 -0truefalsetrue
1 与字符串 '1'falsefalsefalse
同一个对象的两个引用truetruetrue
分别创建、内容相同的对象falsefalsefalse

=== 对应规范中的 IsStrictlyEqual;Object.is 使用 SameValue。两者的差异集中在 NaN 和正负零:Object.is 把 NaN 视为与自身相同,但区分 +0、-0。因此,不能把它笼统描述成 === 的“更严格版本”。SameValueZero 则让 NaN 与自身匹配,同时把两种零归为相同。这里的 Zero 指对正负零的处理,不表示所有假值都相同。参见 MDN Object.is 与 ECMAScript SameValueZero。

NaN 的 typeof 结果仍是 'number'。它通常表示某次数值运算或转换没有得到有效数值;Object.is(NaN, NaN) 为 true 并不会让 NaN 变成有效业务输入。需要拒绝这样的结果时,应单独验证输入规则。

正负零也并非只有显示差异:1 / +0 得到 Infinity,1 / -0 得到 -Infinity。如果后续算法关心零的符号,比较和存储规则都要保留这一区别;普通集合去重则往往不需要区分它们。

二、都不做类型转换,也不递归比较对象

本文的三种规则都不会把字符串 '1' 先转换成数字 1,也不会把 false 转换成 0;null 与 undefined 同样不同。BigInt 的 1n 不等于 Number 的 1。BigInt 没有独立的负零,所以 0n 与 -0n 在这三种规则下都相同。

对于对象,比较的是两个值是否指向同一个对象,而不是字段是否一致。两个分别创建的 { id: 1 } 不会因为内容一样就相等;数组、函数和包装对象也不会自动展开内容比较。new Number(3) 是对象,不会在这里自动拆成数字 3。两个 Symbol('id') 也不是同一个 Symbol,仅描述文本一样没有作用。

另一个容易误用的场景是变化检测:保存一个对象引用之后原地修改其内部字段,再用 Object.is 与原引用比较,结果仍为 true。这个比较没有保存历史快照,不能回答“字段曾经是否改变”。这些身份与类型规则可对照 MDN 相等性指南 和 ECMAScript SameValueNonNumber。

三、includes 与 indexOf 的差异不止返回类型

Array.prototype.includes 使用 SameValueZero,返回布尔值;indexOf 使用严格相等,返回首个匹配索引,没有匹配则返回 -1。所以 [NaN].includes(NaN) 为 true,而 [NaN].indexOf(NaN) 为 -1。两者都能用 +0 找到 -0,也都不会把 '1' 当作 1。需要定位 NaN 的下标时,可以显式使用 findIndex(Number.isNaN),而不是期待 indexOf 改变比较规则。依据:MDN includes、MDN indexOf。

稀疏数组还存在另一层区别:在相应索引没有自身或继承属性的情况下,includes 会把该空位按 undefined 读取,indexOf 则跳过它。因此,将 indexOf(value) !== -1 替换成 includes(value),既要考虑 NaN,也要考虑空位。下方第 8 组只把新建测试数组的原型设为 null,排除继承数字索引的干扰;它不修改全局 Array.prototype,也不建议业务数组普遍采用这一做法。

四、Map 和 Set 的“同一个”如何定义

Set 的成员判定、Map 的键匹配,在可观察的相等语义上采用 SameValueZero:多个 NaN 只对应一个成员或键,+0 与 -0 也不能充当两个不同的键;但数字 1 与字符串 '1' 可以同时存在,两个不同对象也可以同时存在。Map 再次设置等价键时,会替换该键对应的值。参见 MDN Set 和 MDN Map。

阅读当前规范时,会看到 Map 的操作先经 CanonicalizeKeyedCollectionKey 将 -0 规范成 +0,再以 SameValue 匹配。这个写法并没有让 Map 区分两种零;它与上述匹配结果一致。第 10 组还检查了迭代得到的零键是 +0。规范依据:Map.prototype.set 与 键规范化操作。

如果业务需要“同一用户编号就视为同一个人”,应明确选取并规范业务键,再决定是否允许数字编号与字符串编号混用。Set 不会自动按 id 去重,Object.is 也不会自动理解记录的业务含义。

五、完整代码:12 组可以失败的断言

把以下完整代码保存为 complete.cjs,然后分别执行 node complete.cjs 与 node --use-strict complete.cjs。脚本仅依赖 Node.js 内置断言模块,不安装包,不使用网络、随机数或计时器。本次实测环境为 Node.js v24.19.0;普通启动、增加 --use-strict 参数两种方式均通过。代码自身已声明 'use strict',并检查函数调用的 this,确保实际处于严格模式;不能只凭命令参数推断 CommonJS 文件是否启用严格模式。严格模式不会改变本文三种相等规则。

前 6 组验证基础语义;第 7 至 10 组验证数组、Set、Map 的具体行为;第 11 组在固定的 18 个样本上做 324 次两两比较,交叉检查 SameValueZero 辅助函数与 includes;第 12 组让同一份输入选择不同比较器,观察去重结果。样本测试不是对所有可能程序的证明。

'use strict';

const assert = require('node:assert/strict');
assert.equal((function () { return this; })(), undefined);

const strictEqual = (a, b) => a === b;
const sameValueZero = (a, b) => a === b || (a !== a && b !== b);
const comparators = [strictEqual, Object.is, sameValueZero];
let passed = 0;

function check(name, test) {
  test();
  passed += 1;
  console.log(`PASS ${String(passed).padStart(2, '0')} ${name}`);
}

function expectAll(a, b, expected) {
  for (const equal of comparators) {
    assert.equal(equal(a, b), expected);
  }
}

check('ordinary values and no coercion', () => {
  for (const value of [undefined, null, true, false, '', 'JS', 42, Infinity]) {
    expectAll(value, value, true);
  }
  for (const [a, b] of [[1, '1'], [0, false], [null, undefined], [1n, 1]]) {
    expectAll(a, b, false);
  }
});

check('NaN is still a Number value', () => {
  const invalid = Number('not-a-number');
  assert.equal(typeof invalid, 'number');
  assert.equal(Number.isNaN(invalid), true);
  assert.equal(strictEqual(invalid, NaN), false);
  assert.equal(Object.is(invalid, NaN), true);
  assert.equal(sameValueZero(invalid, NaN), true);
  expectAll(NaN, 'NaN', false);
});

check('signed zero can affect later arithmetic', () => {
  assert.equal(strictEqual(+0, -0), true);
  assert.equal(Object.is(+0, -0), false);
  assert.equal(sameValueZero(+0, -0), true);
  assert.equal(Object.is(-0, -0), true);
  assert.equal(1 / +0, Infinity);
  assert.equal(1 / -0, -Infinity);
});

check('object identity does not inspect nested content', () => {
  const left = { profile: { score: 1 } };
  const alias = left;
  const right = { profile: { score: 1 } };
  expectAll(left, alias, true);
  expectAll(left, right, false);
  left.profile.score = 2;
  expectAll(left, alias, true);
  expectAll([1, 2], [1, 2], false);
});

check('Symbol identity and BigInt values', () => {
  const token = Symbol('id');
  expectAll(token, token, true);
  expectAll(token, Symbol('id'), false);
  expectAll(Symbol.for('equality-demo'), Symbol.for('equality-demo'), true);
  expectAll(123n, 123n, true);
  expectAll(0n, -0n, true);
  expectAll(0n, 0, false);
});

check('boxed values are not unboxed by equality', () => {
  const boxed = new Number(3);
  expectAll(boxed, 3, false);
  expectAll(boxed, new Number(3), false);
  expectAll(boxed, boxed, true);
  let calls = 0;
  const guarded = {
    [Symbol.toPrimitive]() {
      calls += 1;
      throw new Error('Conversion must not run');
    }
  };
  expectAll(guarded, 3, false);
  expectAll(guarded, guarded, true);
  assert.equal(calls, 0);
});

check('includes and indexOf disagree on NaN', () => {
  const values = [NaN, -0, 1];
  assert.equal(values.includes(NaN), true);
  assert.equal(values.indexOf(NaN), -1);
  assert.equal(values.findIndex(Number.isNaN), 0);
  assert.equal(values.includes(+0), true);
  assert.equal(values.indexOf(+0), 1);
  assert.equal(values.includes('1'), false);
  assert.equal(values.indexOf('1'), -1);
  const record = { id: 1 };
  assert.equal([record].includes(record), true);
  assert.equal([record].indexOf(record), 0);
  assert.equal([record].includes({ id: 1 }), false);
});

check('array holes are a separate search distinction', () => {
  const sparse = new Array(1);
  Object.setPrototypeOf(sparse, null);
  assert.equal(Array.prototype.includes.call(sparse, undefined), true);
  assert.equal(Array.prototype.indexOf.call(sparse, undefined), -1);
  assert.equal([undefined].indexOf(undefined), 0);
});

check('Set merges NaN and signed zeros, not object copies', () => {
  const left = { id: 1 };
  const right = { id: 1 };
  const values = new Set([NaN, Number('bad'), -0, +0, 1, '1', left, right, left]);
  assert.equal(values.size, 6);
  assert.equal(values.has(NaN), true);
  assert.equal(values.has(-0), true);
  assert.equal(values.has(+0), true);
  assert.equal(values.has(left), true);
  assert.equal(values.has({ id: 1 }), false);
});

check('Map updates equivalent keys and keeps object identities', () => {
  const values = new Map();
  values.set(NaN, 'first');
  values.set(Number('bad'), 'updated');
  values.set(-0, 'negative');
  values.set(+0, 'zero');
  assert.equal(values.size, 2);
  assert.equal(values.get(NaN), 'updated');
  assert.equal(values.get(-0), 'zero');
  const keys = Array.from(values.keys());
  assert.equal(Object.is(keys[1], +0), true);
  assert.equal(Object.is(keys[1], -0), false);
  values.set(1, 'number');
  values.set('1', 'string');
  const key = { id: 1 };
  values.set(key, 'object');
  assert.equal(values.size, 5);
  assert.equal(values.get(key), 'object');
  assert.equal(values.has({ id: 1 }), false);
});

check('SameValueZero helper agrees with includes on fixed samples', () => {
  const shared = {};
  const symbol = Symbol('sample');
  const samples = [undefined, null, false, true, '', '0', 0, -0, 1,
    Infinity, -Infinity, NaN, 0n, 1n, symbol, Symbol('sample'), shared, {}];
  for (const a of samples) {
    for (const b of samples) {
      assert.equal(sameValueZero(a, b), [a].includes(b));
    }
  }
});

check('an explicit comparator changes deduplication semantics', () => {
  function uniqueWith(values, equal) {
    const result = [];
    for (const value of values) {
      if (!result.some((seen) => equal(seen, value))) result.push(value);
    }
    return result;
  }
  const input = [NaN, NaN, +0, -0];
  const strict = uniqueWith(input, strictEqual);
  const same = uniqueWith(input, Object.is);
  const zero = uniqueWith(input, sameValueZero);
  assert.equal(strict.length, 3);
  assert.equal(same.length, 3);
  assert.equal(zero.length, 2);
  assert.equal(Number.isNaN(strict[1]), true);
  assert.equal(Object.is(same[1], +0), true);
  assert.equal(Object.is(same[2], -0), true);
  assert.equal(Object.is(zero[1], +0), true);
});

assert.equal(passed, 12);
console.log('All 12 assertion groups passed.');

其中 sameValueZero 是本文定义的普通函数,不是 JavaScript 提供的同名全局 API。表达式的前半段处理严格相等的情况,后半段只为两个 NaN 补上匹配;它不会调用对象的类型转换方法。第 6 组使用一个会抛错的 Symbol.toPrimitive 方法检验这一点。

实际运行输出如下,两种启动方式的输出一致:

PASS 01 ordinary values and no coercion
PASS 02 NaN is still a Number value
PASS 03 signed zero can affect later arithmetic
PASS 04 object identity does not inspect nested content
PASS 05 Symbol identity and BigInt values
PASS 06 boxed values are not unboxed by equality
PASS 07 includes and indexOf disagree on NaN
PASS 08 array holes are a separate search distinction
PASS 09 Set merges NaN and signed zeros, not object copies
PASS 10 Map updates equivalent keys and keeps object identities
PASS 11 SameValueZero helper agrees with includes on fixed samples
PASS 12 an explicit comparator changes deduplication semantics
All 12 assertion groups passed.

六、从业务含义反推比较方式

  • 通常的无隐式转换比较,可以选 ===,但要知道 NaN 不会匹配自身。

  • 需要将两个 NaN 视为同值、又要保留正负零差异时,选择 Object.is。

  • 希望集合成员判定能找到 NaN,并合并正负零时,includes、Set、Map 的语义更合适。

  • 需要“字段一样”或“同一条业务记录”时,先定义字段范围、编号类型及缺失值规则,不能直接把以上任一种比较当成深比较。

第 12 组的 uniqueWith 只是显式选择比较语义的教学示例:=== 与 Object.is 的结果长度虽然都为 3,保留下来的元素却不同,一个保留两个 NaN,另一个保留两种零。不要只看去重后的长度,也不要把这个示例宣称为高性能通用去重库。

资料核验日期:2026 年 10 月 21 日(北京时间)。文中引用 TC39 在线规范与 MDN 当前页面;在线规范是持续更新文本,页面年份不作为本文所述特性的新发布日期。上述行为是现有语言语义,不是当日新功能公告。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。