【问题标题】:Is an empty array always interpreted as TRUE?空数组是否总是被解释为 TRUE?
【发布时间】:2014-04-09 12:22:46
【问题描述】:

所有浏览器版本都是这样吗?意思是,一个空数组总是被认为是 TRUE,而永远不会像布尔表示那样被认为是 FALSE?

var x = [];

if(x)
   alert('this could be an empty array');
else
    alert('this could NEVER be an empty array');

【问题讨论】:

  • 是的。这就是为什么你会使用类似 isempty/isset 或 count 来查看它是否为空的原因

标签: javascript arrays truthiness


【解决方案1】:

根据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 中的另一个问题

【讨论】:

    【解决方案2】:

    数组是真实的,是的。如果您想要一种简单的方法来检查是否为空,请使用 length 属性:

    var x = [];
    
    if(x.length)
        alert('this array is not empty');
    

    【讨论】:

      【解决方案3】:

      是的。所有对象都是真实的。总是。

      【讨论】:

        【解决方案4】:

        是的。数组是一个对象。所以这是真的。而 null/undefined 为 false

        【讨论】:

          【解决方案5】:

          默认情况下,这些东西在 javascript 中被视为 false。

          1. 未定义
          2. '' 或 "" [空字符串]
          3. 0 [零]

          【讨论】:

          • “默认”?如果您要说这样的话,您还应该至少粗略地提及何时该行为不适用。 (虽然我想不出以上不正确的情况。)
          • 简单,你使用这些以外的结果都是真的。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-11-17
          • 2010-10-17
          • 1970-01-01
          • 2021-03-09
          • 2015-07-28
          • 1970-01-01
          • 2019-10-09
          相关资源
          最近更新 更多