Possible Duplicate:
How to detect if a variable is an array
I have a simple question:
How do I detect if a parameter passed to my javascript function is an array? I don't believe that I can test:
if (typeof paramThatCouldBeArray == 'array')
So is it possible?
How would I do it?
Thanks in advance.
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.
来源:https://stackoverflow.com/questions/2763024/detect-if-parameter-passed-is-an-array-javascript