用于判断对象是否为Array的JavaScript方式

Dam*_*ien 8 javascript

判断对象是否为数组的"正确"方法是什么?

function isArray(o){??? }

CMS*_*CMS 9

The best way:

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

The ECMAScript 5th Edition Specification defines a method for that, and some browsers, like Firefox 3.7alpha, Chrome 5 Beta, and latest WebKit Nightly builds already provide a native implementation, so you might want to implement it if not available:

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

  • @Rixius,好吧,如果有人替换了内置方法,没有太多事情可做,想象一下:`Object.prototype.toString = function(){return"[object Array]"; ``即使使用严格等于`===`运算符,该函数也将始终返回`true`.克罗克福德说:"总是使用`===`",我说:了解类型强制来决定哪个运营商使用. (3认同)