Detect if parameter passed is an array? Javascript [duplicate]

邮差的信 提交于 2019-12-02 19:58:19
if (param instanceof Array)
    ...

Edit. As of 2016, there is a ready-built method that catches more corner cases, Array.isArray, used as follows:

if (Array.isArray(param))
    ...

This is the approach jQuery 1.4.2 uses:

var toString = param.prototype.toString;
var isArray = function(obj) {
        return toString.call(obj) === "[object Array]";
    }

I found this here:

function isArray(obj) {
    return obj.constructor == Array; 
}

also this one

function isArray(obj) {
    return (obj.constructor.toString().indexOf(”Array”) != -1);
}

You can test the constructor property:

if (param.constructor == Array) {
    ...
}

Though this will include objects that have an array prototype,

function Stack() {
}
Stack.prototype = [];

unless they also define constructor:

Stack.prototype.constructor = Stack;

or:

function Stack() {
    this.constructor = Stack;
}

Some days ago I was building a simple type detection function, maybe its useful for you:

Usage:

//...
if (typeString(obj) == 'array') {
  //..
}

Implementation:

function typeString(o) {
  if (typeof o != 'object')
    return typeof o;

  if (o === null)
      return "null";
  //object, array, function, date, regexp, string, number, boolean, error
  var internalClass = Object.prototype.toString.call(o)
                                               .match(/\[object\s(\w+)\]/)[1];
  return internalClass.toLowerCase();
}

The second variant of this function is more strict, because it returns only object types described in the ECMAScript specification (possible output values: "object", "undefined", "null", and "function", "array", "date", "regexp", "string", "number", "boolean" "error", using the [[Class]] internal property).

Duck Typying

Actually, you don't necessarily want to check that an object is an array. You should duck type it and the only thing you want that object to implement is the length property. After this you can transform it into an array:

var arrayLike = {
    length : 3,

    0: "foo"
};

// transform object to array
var array = Array.prototype.slice.call(arrayLike);

JSON.stringify(array); // ["foo", null, null]

Array.prototype.slice.call(object) will transform into an array every object that exposes a length property. In the case of strings for example:

var array = Array.prototype.slice.call("123");
JSON.stringify(array); // ["1", "2", "3"]

Well, this technique it's not quite working on IE6 (I don't know about later versions), but it's easy to create a small utility function to transform objects in arrays.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!