简体   繁体   English

为什么`typeof false || undefined`返回“布尔值”

[英]Why does `typeof false || undefined` returns “boolean”

I've just executed the following in console: 我刚刚在控制台中执行了以下命令:

typeof false || undefined // "boolean"

While I expected it to return "undefined", since 虽然我希望它返回“未定义”,但是

typeof undefined // "undefined"

Why did it return "boolean"? 为什么返回“布尔值”? Isn't the OR operator supposed to return the last argument if previous evaluated to falsey values? 如果先前运算为假值,则OR运算符是否不应该返回最后一个参数? So that false || undefined 如此false || undefined false || undefined returns undefined and typeof is executed against undefined ? false || undefined返回undefined并且对undefined执行typeof吗?

You're not observing operator precedence! 您没有遵守运算符的优先级!

> typeof false || boolean  // (typeof false) || boolean
"boolean"
> typeof (false || boolean)
"undefined"

The OR operator returns the left argument as long as it isn't falsy. 只要OR符不是伪造的, OR运算符就会返回left参数。

In your example, we've got this: 在您的示例中,我们得到了以下信息:

(typeof false) || undefined

typeof false returns "boolean" , which isn't falsy, so it is returned rather than undefined . typeof false返回"boolean" ,这不是虚假的,因此返回而不是undefined

Consider the code : 考虑代码:

typeof false || undefined

typeof false will return "boolean" , so it will become "boolean" || undefined typeof false将返回“ boolean”,因此它将变为"boolean" || undefined "boolean" || undefined

The final output will be "boolean" 最终输出将为“布尔值”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在JavaScript中将value与undefined的比较返回false? - Why does comparing value with undefined returns false in JavaScript? 为什么“真|| 不明确的? 未定义:假;” 返回“未定义”? - why “true || undefined ? undefined : false;” returns “undefinied”? 为什么JSLint告诉我使用“=== undefined”而不是“typeof ... ==='undefined'”? - Why does JSLint tell me to use “=== undefined” instead of “typeof … === 'undefined'”? 为什么“typeof + ''”返回'number'? - Why “typeof + ''” returns 'number'? 为什么typeof让==='undefined'? - Why is typeof let === 'undefined'? 为什么`int(0)和boolean`返回`int(0)`而不是`boolean(false)`? - Why `int(0) and boolean` returns `int(0)` instead `boolean(false)`? 为什么 typeof Array 返回“函数”而 typeof [数组变量] 返回“对象”? - Why does typeof Array returns “function” and typeof [array variable] returns an “Object”? 为什么“undefined equals false”返回 false? - Why does "undefined equals false" return false? JavaScript typeof Typeahead返回未定义 - Javascript typeof Typeahead returns undefined 为什么 performance.hasOwnProperty('getEntries') 返回 false 而 typeof performance.getEntries 返回 function? - Why performance.hasOwnProperty('getEntries') returns false while typeof performance.getEntries returns function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM