Comprobar si el objeto es matriz?


Estoy tratando de escribir una función que acepte una lista de cadenas, o una sola cadena. Si es una cadena, entonces quiero convertirlo en una matriz con solo un elemento. Entonces puedo repetirlo sin miedo a un error.

Entonces, ¿cómo compruebo si la variable es un array?


He redondeado las diversas soluciones a continuación y creado una prueba jsperf.

Author: mpen, 2011-01-23

30 answers

En los navegadores modernos se puede hacer

Array.isArray(obj)

(Compatible con Chrome 5, Firefox 4.0, IE 9, Opera 10.5 y Safari 5)

Para la compatibilidad con versiones anteriores, puede agregar lo siguiente

# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

Si usas jQuery puedes usar jQuery.isArray(obj) o $.isArray(obj). Si usas subrayado puedes usar _.isArray(obj)

Si no necesita detectar matrices creadas en diferentes marcos, también puede usar instanceof

obj instanceof Array
 410
Author: Fela Winkelmolen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-20 21:16:00

El método dado en el estándar ECMAScript para encontrar la clase de Objeto es usar el método toString de Object.prototype.

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
    alert( 'Array!' );
}

O puedes usar typeof para probar si es una cadena:

if( typeof someVar === 'string' ) {
    someVar = [ someVar ];
}

O si no te preocupa el rendimiento, podrías simplemente hacer un concat a un nuevo Array vacío.

someVar = [].concat( someVar );

También está el constructor que puedes consultar directamente:

if (somevar.constructor.name == "Array") {
    // do something
}

Echa un vistazo a un tratamiento completo de @ T. J. Crowder blog, como publicado en su comentario a continuación.

Echa un vistazo a este benchmark para tener una idea de qué método funciona mejor: http://jsben.ch/#/QgYAV

From @Bharath convertir cadena a matriz usando Es6 para la pregunta hecha:

const convertStringToArray = (object) => {
   return (typeof object === 'string') ? Array(object) : object 
}

Supongamos:

let m = 'bla'
let n = ['bla','Meow']
let y = convertStringToArray(m)
let z = convertStringToArray(n)
console.log('check y: '+JSON.stringify(y)) . // check y: ['bla']
console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']
 1875
Author: user113716,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-28 23:30:09

Primero verificaría si su implementación soporta isArray:

if (Array.isArray)
    return Array.isArray(v);

También puede intentar usar el operador instanceof

v instanceof Array
 1228
Author: ChaosPandion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-23 18:55:46

JQuery también ofrece $.isArray() método:

var a = ["A", "AA", "AAA"];

if($.isArray(a)) {
  alert("a is an array!");
} else {
  alert("a is not an array!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 284
Author: janr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 07:41:25

Este es el más rápido entre todos los métodos (todos los navegadores compatibles):

function isArray(obj){
    return !!obj && obj.constructor === Array;
}
 90
Author: shinobi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-19 08:37:44

Imagine que tiene esta matriz a continuación:

var arr = [1,2,3,4,5];

Javascript (navegadores nuevos y antiguos):

function isArray(arr) {
  return arr.constructor.toString().indexOf("Array") > -1;
}

O

function isArray(arr) {
  return arr instanceof Array;
}

O

function isArray(arr) {
  return Object.prototype.toString.call(arr) === '[object Array]';
}

Entonces llámalo así:

isArray(arr);

Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Array.isArray(arr);

JQuery:

$.isArray(arr);

Angular:

angular.isArray(arr);

Subrayado y Lodash:

_.isArray(arr);
 35
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-17 02:44:52

Array.isArray funciona rápido, pero no es compatible con todas las versiones de los navegadores. Así que usted podría hacer una excepción para los demás y utilizar el método universal:

    Utils = {};    
    Utils.isArray = ('isArray' in Array) ? 
        Array.isArray : 
        function (value) {
            return Object.prototype.toString.call(value) === '[object Array]';
        }
 31
Author: CruorVult,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-18 11:18:11

Función simple para comprobar esto:

function isArray(object)
{
    if (object.constructor === Array) return true;
    else return false;
}
 20
Author: MidnightTortoise,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-04 17:56:10

Puede probar este enfoque: http://web.archive.org/web/20100424091244/http://www.ajaxdr.com/code/javascript-version-of-phps-is_array-function/

EDITAR: además, si ya está usando jQuery en su proyecto, puede usar su función $.isArray () .

 16
Author: André Paramés,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-14 11:06:21

Como dice MDN aquí :

Use Array.Objeto isArray o .prototipo.toString.llamar a para diferenciar objetos regulares de arrays

Así:

  • Object.prototype.toString.call(arr) === '[object Array]', o

  • Array.isArray(arr)

 13
Author: ajax333221,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-14 21:02:15

Puede comprobar el tipo de su variable si es una matriz con;

var myArray=[];

if(myArray instanceof Array)
{
....
}
 12
Author: Ahmet DAL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-15 08:58:07

Haría una función para probar el tipo de objeto con el que está tratando...

function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }

// tests
console.log(
  whatAmI(["aiming","@"]),
  whatAmI({living:4,breathing:4}),
  whatAmI(function(ing){ return ing+" to the global window" }),
  whatAmI("going to do with you?")
);

// output: Array Object Function String

Entonces puede escribir una declaración if simple...

if(whatAmI(myVar) === "Array"){
    // do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
    // do string stuff
}
 12
Author: Billy Moon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 07:46:17

Solo hay una solución de línea para esta pregunta

x instanceof Array

Donde x es la variable devolverá true si x es una matriz y false si no lo es.

 11
Author: Vikash Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-08 12:48:15

Hago esto de una manera muy simple. Funciona para mí. ¿Algún inconveniente?

Array.prototype.isArray = true;

a=[]; b={};
a.isArray  // true
b.isArray  // (undefined -> false)
 10
Author: rsbkk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-04 06:58:20

Este es mi intento de mejorar esta respuesta teniendo en cuenta los comentarios:

var isArray = myArray && myArray.constructor === Array;

Se deshace del if / else, y da cuenta de la posibilidad de que el array sea nulo o indefinido

 10
Author: George Jempty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:51

Https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray

Array.isArray = Array.isArray || function (vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
};
 9
Author: Safareli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-01 05:32:31

He actualizado el jsperf fiddle con dos métodos alternativos, así como la comprobación de errores.

Resulta que el método que define un valor constante en los prototipos 'Object' y 'Array' es más rápido que cualquiera de los otros métodos. Es un resultado algo sorprendente.

/* Initialisation */
Object.prototype.isArray = function() {
  return false;
};
Array.prototype.isArray = function() {
  return true;
};
Object.prototype._isArray = false;
Array.prototype._isArray = true;

var arr = ["1", "2"];
var noarr = "1";

/* Method 1 (function) */
if (arr.isArray()) document.write("arr is an array according to function<br/>");
if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");
/* Method 2 (value) - **** FASTEST ***** */
if (arr._isArray) document.write("arr is an array according to member value<br/>");
if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");

Estos dos métodos no funcionan si la variable toma el valor indefinido, pero funcionan si está seguro de que tienen un valor. Con respecto a la comprobación con rendimiento en mente si un valor es una matriz o un solo valor, el segundo método parece un método rápido válido. Es un poco más rápido que 'instanceof' en Chrome, el doble de rápido que el segundo mejor método en Internet Explorer, Opera y Safari (en mi máquina).

 9
Author: le_top,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-01 11:10:28

Sé que la gente está buscando algún tipo de enfoque de javascript sin procesar. Pero si quieres pensar menos, echa un vistazo aquí: http://underscorejs.org/#isArray

_.isArray(object) 

Devuelve true si object es un Array.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
 8
Author: Eugene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-28 13:27:56

La mejor solución que he visto es un reemplazo entre navegadores para typeof. Compruebe la solución de Angus Croll aquí.

La versión TL;DR está debajo, pero el artículo es una gran discusión del tema, por lo que debe leerlo si tiene tiempo.

Object.toType = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// ... and usage:
Object.toType([1,2,3]); //"array" (all browsers)

// or to test...
var shouldBeAnArray = [1,2,3];
if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};
 5
Author: John Wundes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-23 17:16:43

Aquí está mi enfoque perezoso:

if (Array.prototype.array_ === undefined) {
  Array.prototype.array_ = true;
}

// ...

var test = [],
    wat = {};

console.log(test.array_ === true); // true
console.log(wat.array_ === true);  // false

Sé que es un sacrilegio "meterse con" el prototipo, pero parece funcionar significativamente mejor que el método recomendado toString .

Nota: Una trampa de este enfoque es que no funcionará a través de iframe límites, pero para mi caso de uso esto no es un problema.

 5
Author: namuol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-06 02:07:47

Hay un buen ejemplo en el libro de Stoyan Stefanov JavaScript Patterns que supone manejar todos los problemas posibles, así como utilizar el método ECMAScript 5 Array.isArray () .

Así que aquí está:

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]";
    };
}

Por cierto, si está utilizando jQuery, puede usar su método }.isArray()

 5
Author: Salvador Dali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-16 22:27:21

Usted podría es el método isArray, pero yo preferiría comprobar con

Object.getPrototypeOf(yourvariable) === Array.prototype

 5
Author: STEEL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-28 17:21:06

Si los únicos dos tipos de valores que se podrían pasar a esta función son una cadena o una matriz de cadenas, manténgalo simple y use una verificación typeof para la posibilidad de cadena:

function someFunc(arg) {
    var arr = (typeof arg == "string") ? [arg] : arg;
}
 4
Author: Tim Down,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-23 19:51:12
function isArray(value) {
    if (value) {
        if (typeof value === 'object') {
            return (Object.prototype.toString.call(value) == '[object Array]')
        }
    }
    return false;
}

var ar = ["ff","tt"]
alert(isArray(ar))
 4
Author: RoboTamer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-30 09:56:27

Una función simple para probar si un valor de entrada es una matriz es la siguiente:

function isArray(value)
{
  return Object.prototype.toString.call(value) === '[object Array]';
}

Esto funciona entre navegadores y con navegadores más antiguos. Esto es extraído de la entrada del blog de T. J. Crowders

 4
Author: Brad Parks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-02 00:29:54

Esta función convertirá casi cualquier cosa en una matriz:

function arr(x) {
    if(x === null || x === undefined) {
        return [];
    }
    if(Array.isArray(x)) {
        return x;
    }
    if(isString(x) || isNumber(x)) {
        return [x];
    }
    if(x[Symbol.iterator] !== undefined || x.length !== undefined) {
        return Array.from(x);
    }
    return [x];
}

function isString(x) {
    return Object.prototype.toString.call(x) === "[object String]"
}

function isNumber(x) {
    return Object.prototype.toString.call(x) === "[object Number]"
}

Utiliza algunas características más nuevas del navegador por lo que es posible que desee polyfill esto para el máximo soporte.

Ejemplos:

> arr(null);
[]
> arr(undefined)
[]
> arr(3.14)
[ 3.14 ]
> arr(1/0)
[ Infinity ]
> gen = function*() { yield 1; yield 2; yield 3; }
[Function: gen]
> arr(gen())
[ 1, 2, 3 ]
> arr([4,5,6])
[ 4, 5, 6 ]
> arr("foo")
[ 'foo' ]

N.B. Las cadenas se convertirán en una matriz con un solo elemento en lugar de una matriz de caracteres. Borra el isString comprueba si lo prefieres al revés.

He usado Array.isArray aquí porque es el más robusto y también más simple.

 4
Author: mpen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-24 16:01:37

La forma más fácil y rápida de comprobar si un objeto es un Array o no.

 var arr = [];
  arr.constructor.name ==='Array'  //return true;

O

arr.constructor ===Array //return true;

O puede hacer una función de utilidad:

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

Uso:

isArray(arr); //return true
 4
Author: sheelpriy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-29 06:25:02

Se podría usar lo siguiente si sabe que su objeto no tiene un método concat.

var arr = [];
if (typeof arr.concat === 'function') {
    console.log("It's an array");
}
 4
Author: yesil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-26 07:00:00
A = [1,2,3]
console.log(A.map==[].map)

En busca de la versión más corta aquí es lo que tengo hasta ahora.

Tenga en cuenta que no hay una función perfecta que siempre detecte todas las combinaciones posibles. Es mejor conocer todas las habilidades y limitaciones de tus herramientas que esperar una herramienta mágica.

 3
Author: exebook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-12 02:57:43

Puedes probar esto:

var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();

arr.constructor.prototype.hasOwnProperty('push') //true

obj.constructor.prototype.hasOwnProperty('push') // false
 3
Author: VVL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-25 15:54:37