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

Asked

Viewed 6,632 times

4

I wonder how I can identify which object is or is not one array in Javascript.

I know that in jQuery there is the function $.isArray. But I’d like to learn how to do it without the jQuery.

I tried for the typeof and did not return the expected result.

Example:

typeof([]) // "object"
  • 3

    +1 hair without jQuery :)

3 answers

10


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

Example: Array.isArray([]);

Source: http://phpdojo.com.br/javascript/arrays-e-objetos-em-javascript/

// 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. Switching on kids, is a native method in Javascript that returns the type of an Operand.

5

You can try it like this:

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

will return True or False

  • [] instanceof Array functionary?

  • Yes, if you user list instanceof Array will also return you True or False

3

Another way:

[].constructor === Array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.