jingchaocheng / Lodash

Lodash 源码解析
MIT License
0 stars 1 forks source link

eq #25

Open jingchaocheng opened 4 years ago

jingchaocheng commented 4 years ago

执行 SameValueZero 比较两者的值,来确定它们是否相等。

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-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) {
  // http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero
  // samevaluezero 中 NaN 与 NaN 返回 true
  // 前半段 value === other 
  // 后半段 (value !== value && other !== other) 判断 value 与 other 都是 NaN 返回 true
  return value === other || (value !== value && other !== other)
}

export default eq

判断 NaN

  1. value !== value // NaN 与自身不相等
  2. isNaN(value) // 会自行将参数转换成数字,不建议使用
  3. Number.isNaN(value) // 只有 value 为 NaN 时才返回 true
  4. Object.is(value, NaN)