gpt4 book ai didi

JavaScript/jQuery : Check if two values are equal regardless of data type?

转载 作者:行者123 更新时间:2023-12-02 14:11:33 25 4
gpt4 key购买 nike

我有一个 if 条件,我需要检查 A 是否与 B 具有相同的值,无论数据类型如何,例如

if (A == B) {
//body of if statement
}

但是如果存在 ==,服务器检查验证将拒绝。它会要求将其更改为 === (但我无法更改它)。

我如何实现这一点,其中 AB 的可能值和类型是

String, Number, null, '', undefined, NaN

看起来很简单,但可能只是一个逻辑错误......:)

最佳答案

从根本上来说,== 存在有效的用例,因此我建议找到任何可以更改该规则的人,并让他们这样做。

如果没有,您可以自己编写一个函数来执行 == 的功能,称为 abstract equality comparison algorithm ,然后使用该函数而不是 ==:

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then
    1. Return the result of performing Strict Equality Comparison x === y.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

规范中明确定义了上面使用的每个抽象操作的确切实现。

关于JavaScript/jQuery : Check if two values are equal regardless of data type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39512046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com