所有浏览器版本都是这种情况吗?意思是,空数组始终被视为 TRUE 而绝不会像 bool 表示那样被视为 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 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中的另一个问题
关于javascript - 空数组是否总是被解释为 TRUE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22962411/