Javascript:空对象是假的吗? [英] Javascript: Is an empty object a falsy one?
问题描述
空对象未定义,如此var empty_obj = {}。
未定义的将是假的。但我注意到
empty_obj || 3将返回empty_obj而不是3.
为什么?
The empty object is undefined, like this var empty_obj = {}. An undefined will be a false one. But I notice that empty_obj || 3 will return the empty_obj not 3. Why is that?
推荐答案
空对象不 undefined。
The empty object is not undefined.
console.log({} === undefined); // false
console.log(typeof {}); // object
这是一个真正的价值:
if ({}) console.log('truthy'); // truthy
它甚至有一些属性:
console.log(typeof {}.hasOwnProperty); // function
JS中唯一的假值是 0
, false
, null
, undefined
,空字符串, NaN
。
The only falsy values in JS are 0
, false
, null
, undefined
, empty string, and NaN
.
您可能会对此感到困惑返回值 var =
语句。这些将始终在Chrome控制台中显示为 undefined
:
You may be confused by the return value of var =
statements. These will always show as undefined
in the Chrome console:
> var obj = {}
undefined
> var x = 100
undefined
> var y = "potato"
undefined
仅仅因为 var =
语句返回undefined并不意味着该值未定义。虽然,如果没有 var
,分配会返回分配的值:
Just because the var =
statement returns undefined doesn't mean the value was undefined. Although, without the var
, assignments do return the value being assigned:
> obj = {}
{}
> x = 100
100
> y = "potato"
"potato"
这篇关于Javascript:空对象是假的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!