How do I know if an object is an array in javascript (without jquery)?

3

I would like to know how I can identify whether or not an object is a array in Javascript.

I know that in jQuery there is the $.isArray function. But I'd like to learn to do this without jQuery .

I tried typeof and did not return the expected result.

Example:

typeof([]) // "object"
    
asked by anonymous 29.07.2015 / 14:51

3 answers

7

The Array.isArray () method returns true if an object is an array, and false if it is not.

Example: Array.isArray([]);

Source: link

// Antipadrão
frutas = new Array('banana', 'laranja', 'uva');
 
// Padrão Literal
frutas = ['banana', 'laranja', 'uva'];

//Usando o operador typeof podemos verificar o tipo retornado para a variável, e //conforme disse anteriormente, em Javascript um array é um objeto. Veja abaixo:

alert(typeof frutas); // object

//E usando o método isArray podemos verificar se o objeto é um array:

alert(Array.isArray(frutas)); // true
  

Typeof is a JavaScript Unary Operator. Exchanging as a kid, it's a   native method in JavaScript that returns the type of an Operand.

    
29.07.2015 / 15:20
5

You can try this:

Object.prototype.toString.call( list ) === '[object Array]' )

will return True or False

    
29.07.2015 / 14:55
3

Another way:

[].constructor === Array
    
29.07.2015 / 15:10