所有浏览器版本都是这种情况吗?意思是,一个空数组总是被认为是TRUE而且永远不会像布尔表示那样FALSE吗?
var x = [];
if(x)
alert('this could be an empty array');
else
alert('this could NEVER be an empty array');
答案 0 :(得分:3)
根据ECMA Script 5.1 specification's Boolean expression evaluation function,任何对象将始终被评估为Truthy。因此,数组总是被评估为真实的。
+-----------------------------------------------------------------------+
| Argument Type | Result |
|:--------------|------------------------------------------------------:|
| Undefined | false |
|---------------|-------------------------------------------------------|
| Null | false |
|---------------|-------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
|---------------|-------------------------------------------------------|
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
|---------------|-------------------------------------------------------|
| Object | true |
+-----------------------------------------------------------------------+
根据最后一行,对于任何对象,结果将为true
。
参考:My answer到SO
中的另一个问题答案 1 :(得分:1)
阵列是真的,是的。如果您想要一种简单的方法来检查空虚,请使用length
属性:
var x = [];
if(x.length)
alert('this array is not empty');
答案 2 :(得分:0)
是。所有物品都是真实的。总是
答案 3 :(得分:0)
是。数组是一个对象。这是真的。而null / undefined为false
答案 4 :(得分:0)
默认情况下,这些内容在javascript中被视为false。