比较详情
🌐 Comparison details
- 原始值使用
==运算符 进行比较,NaN 除外。当两边都是 NaN 时,它被视为相同。 - 对象的类型标签应该相同。
- 只有可枚举的"自有"属性被考虑。
- 在可用时,会比较对象构造函数。
- <Error> 名称、消息、原因和错误总是会被比较,即使这些不是可枚举的属性。
- 对象封装器 既作为对象也作为未拆封的值进行比较。
Object属性是无序比较的。- <Map> 键和 <Set> 项目是无序比较的。
- 当两边不同时或任一边遇到循环引用时,递归停止。
- 实现不会测试对象的
[[Prototype]]。 - Symbol 属性未被比较。
- WeakMap、WeakSet 和 <Promise> 实例不会进行结构上的比较。它们只有在引用同一个对象时才相等。任何不同的
WeakMap、WeakSet或Promise实例之间的比较都会导致不相等,即使它们包含相同的内容。 - <RegExp> lastIndex、flags 和 source 总是会被比较,即使它们不是可枚举属性。
以下示例不会抛出 AssertionError,因为使用 == 运算符 比较了原始类型。
🌐 The following example does not throw an AssertionError because the
primitives are compared using the == operator.
import assert from 'node:assert'; // WARNING: This does not throw an AssertionError! assert.deepEqual('+00000000', false);const assert = require('node:assert'); // WARNING: This does not throw an AssertionError! assert.deepEqual('+00000000', false);
"深层"平等意味着还会对子对象的可枚举"自身"属性进行评估:
import assert from 'node:assert'; const obj1 = { a: { b: 1, }, }; const obj2 = { a: { b: 2, }, }; const obj3 = { a: { b: 1, }, }; const obj4 = { __proto__: obj1 }; assert.deepEqual(obj1, obj1); // OK // Values of b are different: assert.deepEqual(obj1, obj2); // AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } } assert.deepEqual(obj1, obj3); // OK // Prototypes are ignored: assert.deepEqual(obj1, obj4); // AssertionError: { a: { b: 1 } } deepEqual {}const assert = require('node:assert'); const obj1 = { a: { b: 1, }, }; const obj2 = { a: { b: 2, }, }; const obj3 = { a: { b: 1, }, }; const obj4 = { __proto__: obj1 }; assert.deepEqual(obj1, obj1); // OK // Values of b are different: assert.deepEqual(obj1, obj2); // AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } } assert.deepEqual(obj1, obj3); // OK // Prototypes are ignored: assert.deepEqual(obj1, obj4); // AssertionError: { a: { b: 1 } } deepEqual {}
如果数值不相等,将抛出一个 AssertionError,message 属性被设置为 message 参数的值。如果 message 参数未定义,则会分配默认的错误消息。如果 message 参数是 <Error> 的实例,则将抛出它而不是 AssertionError。
🌐 If the values are not equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of <Error> then it will be thrown instead of the
AssertionError.