【问题标题】:JavaScript way to tell if an object is an Array [duplicate]JavaScript判断对象是否为数组的方法[重复]
【发布时间】:2011-02-25 08:06:08
【问题描述】:

判断一个对象是否为数组的“正确”方法是什么?

函数 isArray(o) { ??? }

【问题讨论】:

  • 您可能希望提供有关您的环境的更多详细信息,例如:纯 javascript?在浏览器中运行?原型或其他库可用吗?

标签: javascript


【解决方案1】:

最好的办法:

function isArray(obj) {
  return Object.prototype.toString.call(obj) == '[object Array]';
}

ECMAScript 5th Edition Specification 为此定义了一个方法,而some browsers,如 Firefox 3.7alpha、Chrome 5 Beta 和最新的 WebKit Nightly 版本已经提供了本机实现,因此如果不可用,您可能想要实现它:

if (typeof Array.isArray != 'function') {
  Array.isArray = function (obj) {
    return Object.prototype.toString.call(obj) == '[object Array]';
  };
}

【讨论】:

  • 更安全的是return Object.prototype.toString.call(obj) === '[object Array]';,以避免任何可能的胁迫
  • @Rixius:嗯,Object.prototype.toString 方法在规范中是fully describedString 返回值是保证,我看不出有什么好处使用严格的等号运算符,当您知道您正在比较两个字符串值时...
  • 有人可能会抨击Object.prototype.toString 总是比抱歉更安全。
  • @Rixius,好吧,如果有人替换了内置方法,也没什么可做的,想象一下:Object.prototype.toString = function () {return "[object Array]"; }; 即使使用严格的等于 === 运算符,函数也会返回 @987654332 @ 总是。 Crockford 说:“始终使用===”,我说:了解类型强制以决定使用哪个运算符。
  • @CMS 这很有意义,感谢您的回复。
【解决方案2】:

您应该可以使用instanceof 运算符:

var testArray = [];

if (testArray instanceof Array)
    ...

【讨论】:

  • instanceof 唯一的缺点是当您在多帧 DOM 环境中工作时,一帧的数组对象不是另一帧的 Array 构造函数的实例。有关详细信息,请参阅this article
【解决方案3】:

jQuery 解决了很多这样的问题:

jQuery.isArray(obj)

【讨论】:

    【解决方案4】:

    这是我用的:

    function is_array(obj) {
      return (obj.constructor.toString().indexOf("Array") != -1)
    }
    

    【讨论】:

    • 感谢您的回答,我不明白为什么 x.constructor.toString().indexOf("Array") 如果它的数组实例返回 9?你能告诉我吗?
    【解决方案5】:
    function typeOf(obj) {
      if ( typeof(obj) == 'object' )
        if (obj.length)
          return 'array';
        else
          return 'object';
        } else
      return typeof(obj);
    }
    

    【讨论】:

      【解决方案6】:

      您可以使用 Prototype 方法 Object.isArray() 的库定义来测试它:

      function(object) {
        return object != null && typeof object == "object" &&
         'splice' in object && 'join' in object;
      }
      

      【讨论】:

      • Prototype 不再使用该方法,请参阅here 它是如何在 1.6.1 中实现的。
      猜你喜欢
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多