Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 345
Alex Avatar asked May 04 '10 05:05

Alex


People also ask

How do you check if there are duplicates in an array JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How do I check if an object is an array of duplicates?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you check if a number is repeated in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }

How do you know if a parameter is an array?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .


2 Answers

This is the approach jQuery 1.4.2 uses:

var toString = param.prototype.toString; var isArray = function(obj) {         return toString.call(obj) === "[object Array]";     } 
like image 33
James Westgate Avatar answered Oct 05 '22 22:10

James Westgate


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))     ... 
like image 200
Casey Chu Avatar answered Oct 05 '22 21:10

Casey Chu