【问题标题】:Javascript why console.log(typeof "Not a Number" - "Number") prints 'NaN'?Javascript 为什么 console.log(typeof "Not a Number" - "Number") 打印'NaN'?
【发布时间】:2020-05-09 03:51:33
【问题描述】:
我知道并承认
console.log(typeof NaN) // 'number'
但是我需要帮助理解
的逻辑
console.log(typeof "Not a Number" - "Number") // 'NaN'
看看这个
console.log("NaN is normal" - "normal" + "special") // NaNspecial
我看到"NaN is normal" - "normal" 给出了NaN(这是一个number 类型),然后在连接之前将其转换为string。
【问题讨论】:
标签:
javascript
types
nan
typeof
【解决方案1】:
见operator precedence。 typeof 的优先级为 17,减法的优先级为 14。所以
console.log(typeof "Not a Number" - "Number") // 'NaN'
相当于:
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)
同样,- 和 + 具有相同的优先级,并且从左到右工作,所以最终代码相当于:
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")