所有浏览器版本都是这种情况吗?意思是,一个空数组总是被认为是 TRUE 而不是 FALSE 作为布尔表示?
var x = [];
if(x)
alert('this could be an empty array');
else
alert('this could NEVER be an empty array');
所有浏览器版本都是这种情况吗?意思是,一个空数组总是被认为是 TRUE 而不是 FALSE 作为布尔表示?
var x = [];
if(x)
alert('this could be an empty array');
else
alert('this could NEVER be an empty array');
根据ECMA Script 5.1 规范的布尔表达式评估函数,任何对象都将始终被评估为真值。因此,数组将始终被评估为真实。
+-----------------------------------------------------------------------+
| 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
.
参考:我对 SO 中另一个问题的回答
数组是真实的,是的。如果您想要一种简单的方法来检查是否为空,请使用以下length
属性:
var x = [];
if(x.length)
alert('this array is not empty');
是的。所有对象都是真实的。总是。
是的。数组是一个对象。所以这是真的。而 null/undefined 为 false
默认情况下,这些东西在 javascript 中被视为 false。