Javascript 为什么 console.log(typeof "Not a Number" - "Number") 打印 'NaN'?

Nor*_*ldt 4 javascript types typeof nan

我知道并承认

console.log(typeof NaN) // 'number'
Run Code Online (Sandbox Code Playgroud)

但是我需要帮助理解

console.log(typeof "Not a Number" - "Number") // 'NaN'
Run Code Online (Sandbox Code Playgroud)

看着这个

console.log("NaN is normal" - "normal" + "special") // NaNspecial
Run Code Online (Sandbox Code Playgroud)

我看到"NaN is normal" - "normal"给出NaN(这是一种number类型),然后string在连接之前将其转换为 a 。

Cer*_*nce 6

请参阅运算符优先级。typeof优先级为 17,减法优先级为 14。所以

console.log(typeof "Not a Number" - "Number") // 'NaN'
Run Code Online (Sandbox Code Playgroud)

相当于:

console.log(typeof "Not a Number" - "Number") // original line
console.log((typeof "Not a Number") - "Number") // grouping; operator precedence
console.log(("string") - "Number")
console.log("string" - "Number")
// A string can't be meaningfully subtracted from another string, so the result is NaN
console.log(NaN)
Run Code Online (Sandbox Code Playgroud)

同样,-and+具有相同的优先级,从左到右工作,所以最终的代码等价于:

console.log("NaN is normal" - "normal" + "special") // original line
console.log(("NaN is normal" - "normal") + "special")
console.log((NaN) + "special")
// NaN gets coerced to a string and concatenated:
console.log("NaNspecial")
Run Code Online (Sandbox Code Playgroud)