【问题标题】: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 precedencetypeof 的优先级为 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")
    

    【讨论】:

    • 谢谢!这就是我缺少的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 2020-04-19
    • 2020-03-06
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多