返回

Lodash 源码分析:eq 函数的 SameValueZero 规范

前端

在 Lodash 库中,eq 函数是一个用于比较两个值是否相等的函数。它遵循 SameValueZero 规范,该规范定义了四条比较规则:

  1. 如果 x 为 NaN,返回 false。

  2. 如果 y 为 NaN,返回 false。

  3. 如果 x 和 y 的数值一致,返回 true。

  4. 如果 x 为 +0,y 为 -0,或者 x 为 -0,y 为 +0,返回 true。

eq 函数的源码如下:

/**
 * Performs a SameValueZero comparison between two values to determine if they are equivalent.
 *
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * const object = { 'a': 1 };
 * const other = { 'a': 1 };
 *
 * eq(object, object);
 * // => true
 *
 * eq(object, other);
 * // => false
 *
 * eq('a', 'a');
 * // => true
 *
 * eq('a', Object('a'));
 * // => false
 *
 * eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}

让我们通过一些代码示例来理解 eq 函数的用法:

const object = { 'a': 1 };
const other = { 'a': 1 };

eq(object, object); // true
eq(object, other); // false
eq('a', 'a'); // true
eq('a', Object('a')); // false
eq(NaN, NaN); // true

如上所示,eq 函数可以正确地比较两个值是否相等,即使它们是不同的类型。例如,eq('a', Object('a')) 返回 false,因为这两个值虽然看起来相同,但实际上是不同的类型。

eq 函数在 JavaScript 开发中非常有用,它可以用于比较各种类型的值,包括数字、字符串、布尔值、对象和数组等。它可以帮助我们编写更加健壮和可靠的代码。