gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:09:49 25 4
gpt4 key购买 nike

我知道并承认

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在串联之前。

最佳答案

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")

关于Javascript 为什么 console.log(typeof "Not a Number"- "Number") 打印 'NaN' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com