为什么 1 == 1 == 1,而不是 'A' == 'A' == 'A'

Gre*_*les 0 javascript string-comparison

我正在尝试根据配置负载编写灵活的查询逻辑,例如:

{
 "test": "( fieldA == fieldB == fieldC )"
}
Run Code Online (Sandbox Code Playgroud)

当我的应用程序用文本数据替换 'fieldA'、'fieldB' 和 'fieldC' 值时,结果始终为 false。这显然与我混淆了 javascript 运行比较的方式有关(它必须与数据类型和数学排序有关),但是谁能用一个简单的字母数字值示例来解释这一点?

例如 'John Smith' == 'John Smith' == 'John Smith' 总是假的;

LeG*_*GEC 6

x == y == z 不做你认为的:

它转化为(x == y) == z.

随着 javascript==操作符的怪癖:

  • 1 == 1并且'A' == 'A'都翻译成true
  • 然而:true == 1返回true,而true == 'A'不会

您可能想将您的条件重写为:

(x == y) && (x == z)
Run Code Online (Sandbox Code Playgroud)

并且很可能想使用明确的===运算符:

(x === y) && (x === z)
Run Code Online (Sandbox Code Playgroud)

避免诸如您遇到的陷阱(true == 1检查,但不是true === 1