# 相等，还是不等(3) - 真真假假

Last Updated: 2023-02-24

## 入门。

• false
• 0 (zero)
• "" (empty string)
• null
• undefined
• NaN (Not A Number)

PHP 里定义以下为假：

• null // null
• 0 // integer
• 0.0 // float
• "0" // string
• "" // empty string
• false // boolean
• array() // empty array

``````VALUE           if()  empty() isset()
-------------------------------------
null            false true    false
0.0             false true    true
"0"             false true    true
""              false true    true
false           false true    true
array()         false true    true
EVERYTHING_ELSE true  false   true
``````

## 放弃？

`0`和空字符串`""`相等吗？

Python 说：不等

``````>>> 0 == ""
False
``````

Java 说：你疯了吧

``````jshell> 0 == ""
|  Error:
|  bad operand types for binary operator '=='
|    first type:  int
|    second type: java.lang.String
|  0 == ""
|  ^-----^
``````

JavaScript 说：相等，稳稳的

``````> 0 == ""
true
``````

``````> null == undefined
true
``````

``````> "" == undefined
false
> NaN == false
false
``````

``````> NaN === NaN
false
``````

``````jshell> Double.NaN == Double.NaN
\$2 ==> false
``````
``````>>> float('nan') == float('nan')
False
``````

``````\$a = ''; \$b = 0; \$c = '0a';
\$a == \$b; // true
\$b == \$c; // true
\$c == \$a; // false!
``````

## 进阶！

### 关于 NaN

``````> x = NaN ? 'true' : 'false'
'false'
``````

``````jshell> int x = Double.NaN ? 0 : 1;
|  Error:
|  incompatible types: double cannot be converted to boolean
|  int x = Double.NaN ? 0 : 1;
|          ^--------^
``````

`NaN`就是跟任何值都不相等，包括他自己

``````jshell> Double.NaN - Double.NaN
\$1 ==> NaN
``````

``````jshell> Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY
\$2 ==> NaN

jshell> Double.POSITIVE_INFINITY + Double.POSITIVE_INFINITY
\$3 ==> Infinity

jshell> Double.POSITIVE_INFINITY + Double.NEGATIVE_INFINITY
\$4 ==> NaN
``````

`null``undefined`算是一组，只有他们两个互相相等

``````> null == undefined
true
> null == null
true
> undefined == undefined
true
``````

### == vs ===

JavaScript 和 PHP 中都提供两种判断相等的方法：`==``===`

`==`只判断值是不是相等，如果等号两侧是不一样的类型，他们会被转换成相同的类型进行比较，所以是不具有传递性的，才会出现上面 `a==b，b==c``a!=c` 的情况。而`===`是更严格的比较，既包括类型也包括值，因而是具有传递性的。

``````> false == 0
true
> false === 0
false
``````

``````> 1 == '1'
true
> 1 === '1'
false
``````

``````function factory() {
return (a, b) => a + b;
}

const sum1 = factory();
const sum2 = factory();

sum1(1, 2); // => 3
sum2(1, 2); // => 3

sum1 === sum2; // => false
sum1 === sum1; // => true
``````