Comprobar si un valor es un objeto en JavaScript
¿Cómo se comprueba si un valor es un Objeto en JavaScript?
30 answers
Intenta usar typeof(var)
y/o var instanceof something
.
EDITAR: Esta respuesta da una idea de cómo examinar las propiedades de la variable, pero es no una receta a prueba de balas (después de todo, no hay receta en absoluto!) para comprobar si es un objeto, lejos de él. Dado que la gente tiende a buscar algo para copiar desde aquí sin hacer ninguna investigación, recomiendo encarecidamente que recurran al otro, el más votado (¡y correcto!) respuesta.
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-02 10:17:18
Si typeof yourVariable === 'object'
, es un objeto o null. Si desea excluir null, simplemente hágalo yourVariable !== null && typeof yourVariable === 'object'
.
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-03-18 21:02:08
Definamos "objeto" en Javascript . De acuerdo con la MDN docs , cada valor es un objeto o una primitiva:
Primitivo, valor primitivo
Un dato que no es un objeto y no tiene ningún método. JavaScript tiene 5 tipos de datos primitivos: string, number, boolean, null, undefined.
¿Qué es un ¿primitivo?
3
'abc'
true
null
undefined
¿Qué es un objeto (es decir, no un primitivo)?
Object.prototype
- todo desciende de
Object.prototype
-
Function.prototype
Object
Function
-
function C(){}
functions funciones definidas por el usuario
-
C.prototype
the la propiedad prototype de una función definida por el usuario: esto es noC
s prototipo-
new C()
{"new" -ing una función definida por el usuario
-
Math
-
Array.prototype
- arrays
-
{"a": 1, "b": 2}
objects objetos creados usando notación literal -
new Number(3)
wra envolturas alrededor de primitivas - ... muchas otras cosas ...
-
Object.create(null)
- todo desciende de un {[24]]}
Cómo comprobar si un valor es un objeto
instanceof
por en sí mismo no funciona, porque se pierde dos casos:
// oops: isObject(Object.prototype) -> false
// oops: isObject(Object.create(null)) -> false
function isObject(val) {
return val instanceof Object;
}
typeof x === 'object'
no funcionará, debido a falsos positivos (null
) y falsos negativos (funciones):
// oops: isObject(Object) -> false
function isObject(val) {
return (typeof val === 'object');
}
Object.prototype.toString.call
no funcionará, debido a los falsos positivos para todos los primitivos:
> Object.prototype.toString.call(3)
"[object Number]"
> Object.prototype.toString.call(new Number(3))
"[object Number]"
Así que uso:
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
La respuesta de@Daan también parece funcionar:
function isObject(obj) {
return obj === Object(obj);
}
Porque, de acuerdo con el MDN docs :
El constructor de objetos crea un contenedor de objetos para el valor. Si el valor es null o undefined, creará y devolverá un objeto vacío, de lo contrario, devolverá un objeto de un tipo que corresponda al valor dado. Si el valor ya es un objeto, devolverá el valor.
Una tercera forma que parece funcionar (no estoy seguro de si es 100%) es usar Object.getPrototypeOf
que lanza una excepción si su argumento no es un objeto:
// these 5 examples throw exceptions
Object.getPrototypeOf(null)
Object.getPrototypeOf(undefined)
Object.getPrototypeOf(3)
Object.getPrototypeOf('abc')
Object.getPrototypeOf(true)
// these 5 examples don't throw exceptions
Object.getPrototypeOf(Object)
Object.getPrototypeOf(Object.prototype)
Object.getPrototypeOf(Object.create(null))
Object.getPrototypeOf([])
Object.getPrototypeOf({})
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-07-20 14:05:30
El subrayado oficial .js utiliza esta comprobación para averiguar si algo es realmente un objeto
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
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-05 11:50:37
Object.prototype.toString.call(myVar)
volverá:
-
"[object Object]"
si myVar es un objeto -
"[object Array]"
si myVar es una matriz - etc.
Para obtener más información sobre esto y por qué es una buena alternativa a typeof, consulte este artículo.
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-07-25 14:17:20
Me gusta simplemente:
function isObject (item) {
return (typeof item === "object" && !Array.isArray(item) && item !== null);
}
Si el elemento es un objeto JS, y no es una matriz JS, y no es null
if si los tres resultan verdaderos, devuelve true
. Si alguna de las tres condiciones falla, la prueba &&
cortocircuitará y se devolverá false
. La prueba null
se puede omitir si se desea (dependiendo de cómo utilice null
).
DOCS:
Http://devdocs.io/javascript/operators/typeof
Http://devdocs.io/javascript/global_objects/object
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-06-14 16:58:48
Para simplemente comprobar contra Objeto o Matriz sin llamada a función adicional (velocidad). Como también publicado aquí.
IsArray()
isArray = function(a) {
return (!!a) && (a.constructor === Array);
};
console.log(isArray( )); // false
console.log(isArray( null)); // false
console.log(isArray( true)); // false
console.log(isArray( 1)); // false
console.log(isArray( 'str')); // false
console.log(isArray( {})); // false
console.log(isArray(new Date)); // false
console.log(isArray( [])); // true
IsObject () - Nota: use solo para literales de objetos, ya que devuelve false para objetos personalizados, como new Date o new YourCustomObject.
isObject = function(a) {
return (!!a) && (a.constructor === Object);
};
console.log(isObject( )); // false
console.log(isObject( null)); // false
console.log(isObject( true)); // false
console.log(isObject( 1)); // false
console.log(isObject( 'str')); // false
console.log(isObject( [])); // false
console.log(isObject(new Date)); // false
console.log(isObject( {})); // true
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:18:27
Con función Array.isArray
:
function isObject(o) {
return o !== null && typeof o === 'object' && Array.isArray(o) === false;
}
Sin función Array.isArray
:
Me sorprendió cuántos votos positivos para respuestas incorrectas
Solo 1 respuesta pasó mis pruebas!!! Aquí he creado mi versión simplificada:
function isObject(o) {
return o instanceof Object && o.constructor === Object;
}
En cuanto a mí, es claro y simple, y simplemente funciona! Aquí mis pruebas:
console.log(isObject({})); // Will return: true
console.log(isObject([])); // Will return: false
console.log(isObject(null)); // Will return: false
console.log(isObject(/.*/)); // Will return: false
console.log(isObject(function () {})); // Will return: false
UNA VEZ MÁS: ¡no todas las respuestas pasan estas pruebas !!!
En caso de que necesite verificar que el objeto es instancia de clase particular tiene para comprobar constructor con su clase particular, como:
function isDate(o) {
return o instanceof Object && o.constructor === Date;
}
Prueba simple:
var d = new Date();
console.log(isObject(d)); // Will return: false
console.log(isDate(d)); // Will return: true
Como resultado, usted tendrá código estricto y robusto!
En caso de que no cree funciones como isDate
, isError
, isRegExp
, etc usted puede considerar la opción de utilizar estas funciones generalizadas:
function isObject(o) {
return o instanceof Object && typeof o.constructor === 'function';
}
No funcionará correctamente para todos los casos de prueba mencionados anteriormente, pero es lo suficientemente bueno para todos los objetos (simples o construidos).
isObject
no funcionará en caso de Object.create(null)
debido a la implementación interna de Object.create
que se explica aquí pero se puede usar isObject
en una implementación más sofisticada:
function isObject(o, strict = true) {
if (o === null || o === undefined) {
return false;
}
const instanceOfObject = o instanceof Object;
const typeOfObject = typeof o === 'object';
const constructorUndefined = o.constructor === undefined;
const constructorObject = o.constructor === Object;
const typeOfConstructorObject = typeof o.constructor === 'function';
let r;
if (strict === true) {
r = (instanceOfObject || typeOfObject) && (constructorUndefined || constructorObject);
} else {
r = (constructorUndefined || typeOfConstructorObject);
}
return r;
};
Ya se ha creado paquete en npm v1 basado en esta implementación! ¡Y funciona para todos los casos de prueba descritos anteriormente!
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-04-02 20:21:15
OK, vamos a darle este concepto primero antes de responder a su pregunta, en JavaScript Las funciones son Objeto, también null, Objeto, Arrays e incluso Date, por lo que como ve, hay no una forma simple como typeof obj = = = 'object', por lo que todo lo mencionado anteriormente devolverá true , pero hay formas de comprobarlo escribiendo una función o usando marcos de JavaScript, OK:
Ahora, imagine que tiene este objeto que es un objeto real (no null o función o array):
var obj = {obj1: 'obj1', obj2: 'obj2'};
JavaScript puro:
//that's how it gets checked in angular framework
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
O
//make sure the second object is capitalised
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
O
function isObject(obj) {
return obj.constructor.toString().indexOf("Object") > -1;
}
O
function isObject(obj) {
return obj instanceof Object;
}
Simplemente puede usar una de estas funciones como la anterior en su código llamándolas y devolverá true si se trata de un objeto:
isObject(obj);
Si está utilizando un framework JavaScript, por lo general han preparado este tipo de funciones para usted, estas son algunas de ellas:
JQuery:
//It returns 'object' if real Object;
jQuery.type(obj);
Angular:
angular.isObject(obj);
Subrayado y Lodash:
//(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null)
_.isObject(obj);
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-04-12 01:41:05
Depende de lo que quieras decir con "es un objeto". Si desea todo lo que no es un primitivo, es decir, cosas en las que puede establecer nuevas propiedades, esto debería hacer el truco:
function isAnyObject(value) {
return value != null && (typeof value === 'object' || typeof value === 'function');
}
Excluye las primitivas (números planos/NaN
/Infinity
, cuerdas simples, símbolos, true
/false
, undefined
y null
), pero debe volver verdadero para todo lo demás (incluyendo Number
, Boolean
y String
objetos). Tenga en cuenta que JS no define qué objetos" host", como window
o console
, deben devolver cuando se usa con typeof
, por lo que son difíciles de cubrir con un cheque como este.
Si quieres saber si algo es un objeto "simple", es decir, fue creado como un {}
literal o con Object.create(null)
, puedes hacer esto:
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
} else {
var prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
}
}
Editar 2018 : Porque Symbol.toStringTag
ahora permite personalizar la salida de Object.prototype.toString.call(...)
, la función isPlainObject
anterior podría devolver false
en algunos casos incluso cuando el objeto comenzó su vida como un literal. Podría decirse que, por convención, un objeto con una costumbre la etiqueta de cadena ya no es exactamente un objeto plano, pero esto ha enturbiado aún más la definición de lo que es un objeto plano en Javascript.
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-09-28 09:58:22
La forma más razonable de comprobar el tipo de un valor parece el operador typeof
. El único problema es que está horriblemente roto:
- Devuelve
"object"
paranull
, que pertenece al tipo Null. - Devuelve
"function"
para objetos llamables, que pertenecen al tipo de objeto. - Puede devolver (casi) cualquier cosa que desee para objetos no estándar no llamables. Por ejemplo, IE parecía como
"unknown"
. Los únicos resultados prohibidos son"function"
y primitivos tipo.
typeof
solo es confiable para no - null
primitivos. Así que una forma de comprobar si un valor es un objeto sería asegurar que la cadena devuelta por typeof
no corresponde a una primitiva, y que el objeto no es null
. Sin embargo, el problema es que un estándar futuro podría introducir un nuevo tipo primitivo, y nuestro código lo consideraría un objeto. Los nuevos tipos no aparecen con frecuencia, pero por ejemplo ECMAScript 6 introdujo el tipo de símbolo.
Por lo tanto, en lugar de typeof
, solo recomiendo enfoques cuyo resultado varía dependiendo de si el valor es un objeto o no. La siguiente tiene la intención de ser un
Lista completa pero no exhaustiva de formas adecuadas de probar si un valor pertenece al tipo de objeto.
-
Object
constructorEl constructor
Object
coacciona el argumento pasado a un objeto. Si ya es un objeto, se devuelve el mismo objeto.Por lo tanto, puede usarlo para coaccionar el valor a un objeto, y compare estrictamente ese objeto con el valor original.
La siguiente función requiere ECMAScript 3, que introdujo
===
:function isObject(value) { /* Requires ECMAScript 3 or later */ return Object(value) === value; }
Me gusta este enfoque porque es simple y auto-descriptivo, y una comprobación análoga también funcionará para booleanos, números y cadenas. Sin embargo, tenga en cuenta que se basa en el global
Object
no ser sombreado ni alterado. -
Constructores
Cuando instanciasun constructor, se puede devolver un valor diferente al de la instancia recién creada. Pero ese valor será ignorado a menos que sea un objeto.
La siguiente función requiere ECMAScript 3, que permite a los constructores devolver no objetos. Antes de ECMAScript 3 que arrojaba un error, pero las sentencias
try
no existían en ese entonces.function isObject(value) { /* Requires ECMAScript 3 or later */ return new function() { return value; }() === value; }
Aunque un poco menos simple que el ejemplo anterior, este no se basa en ninguna propiedad global, y por lo tanto podría ser el más seguro.
-
this
valorLas especificaciones antiguas de ECMAScript requerían que el valor
this
fuera un objeto. ECMAScript 3 introdujoFunction.prototype.call
, que permitía llamar a una función con un valor arbitrariothis
, pero coaccionado a un objeto.ECMAScript 5 introdujo un modo estricto que eliminó este comportamiento, pero en el modo descuidado todavía podemos (pero posiblemente no deberíamos) confiar en él.
function isObject(value) { /* Requires ECMAScript 3 or later in sloppy mode */ return function() { return this === value; }.call(value); }
-
[[Prototipo]]
Todos los objetos ordinarios tienen una ranura interna llamada [[Prototype]], cuyo valor determina de qué otro objeto hereda. El valor solo puede ser un objeto o
null
. Por lo tanto, puede intentar crear un objeto que herede del valor deseado y comprobar si funcionó.Tanto
Object.create
comoObject.getPrototypeOf
requieren ECMAScript 5.function isObject(value) { /* Requires ECMAScript 5 or later */ try { Object.create(value); return value !== null; } catch(err) { return false; } }
function isObject(value) { /* Requires ECMAScript 5 or later */ function Constructor() {} Constructor.prototype = value; return Object.getPrototypeOf(new Constructor()) === value; }
-
Algunas nuevas formas de ECMAScript 6
ECMAScript 6 introduce algunas nuevas formas indirectas de comprobar si un valor es un objeto. Utilizan lo visto anteriormente enfoque para pasar el valor a algún código que requiere un objeto, envuelto dentro de una instrucción
try
para detectar errores. Algunos ejemplos ocultos, no vale la pena comentarfunction isObject(value) { /* Requires ECMAScript 6 or later */ try { Object.setPrototypeOf({}, value); return value !== null; } catch(err) { return false; } }
function isObject(value) { /* Requires ECMAScript 6 or later */ try { new WeakSet([value]); return true; } catch(err) { return false; } }
Nota: Intencionalmente omití algunos enfoques como Object.getPrototypeOf(value)
(ES5) y Reflect
métodos (ES6) porque llaman a métodos internos esenciales que podrían hacer cosas desagradables, por ejemplo, si value
es un proxy. Por razones de seguridad mis ejemplos solo referencia value
sin acceder a él directamente.
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-28 01:25:28
Prueba esto
if (objectName instanceof Object == false) {
alert('Not an object');
}
else {
alert('An object');
}
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-05-09 13:05:17
Funciones listas para usar para comprobar
function isObject(o) {
return null != o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]';
}
function isDerivedObject(o) {
return !isObject(o) &&
null != o &&
(typeof o === 'object' || typeof o === 'function') &&
/^\[object /.test(Object.prototype.toString.call(o));
}
// Loose equality operator (==) is intentionally used to check
// for undefined too
// Also note that, even null is an object, within isDerivedObject
// function we skip that and always return false for null
Explicación
En Javascript,
null
,Object
,Array
,Date
yfunction
s son todos los objetos. Aunque,null
es un poco artificial. Por lo tanto, es mejor comprobar elnull
primero, para detectar que no es null.-
Comprobar
typeof o === 'object'
garantiza queo
es un objeto. Sin este control,Object.prototype.toString
no tendría sentido, ya que devolvería objeto para todo, incluso paraundefined
ynull
! Por ejemplo:toString(undefined)
devuelve[object Undefined]
!Después de
typeof o === 'object'
comprobar, toString.call(o) es un gran método para comprobar sio
es un objeto, un objeto derivado comoArray
,Date
o afunction
. En la función
isDerivedObject
, comprueba queo
es una función. Porque, función también un objeto, es por eso que está allí. Si no lo hizo, la función volverá como false. Ejemplo:isDerivedObject(function() {})
devolveríafalse
, sin embargo ahora devuelvetrue
.Siempre se puede cambiar la definición de lo que es un objeto. Por lo tanto, uno puede cambiar estas funciones en consecuencia.
Pruebas
function isObject(o) {
return null != o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]';
}
function isDerivedObject(o) {
return !isObject(o) &&
null != o &&
(typeof o === 'object' || typeof o === 'function') &&
/^\[object /.test(Object.prototype.toString.call(o));
}
// TESTS
// is null an object?
console.log(
'is null an object?', isObject(null)
);
console.log(
'is null a derived object?', isDerivedObject(null)
);
// is 1234 an object?
console.log(
'is 1234 an object?', isObject(1234)
);
console.log(
'is 1234 a derived object?', isDerivedObject(1234)
);
// is new Number(1234) an object?
console.log(
'is new Number(1234) an object?', isObject(new Number(1234))
);
console.log(
'is new Number(1234) a derived object?', isDerivedObject(1234)
);
// is function object an object?
console.log(
'is (new (function (){})) an object?',
isObject((new (function (){})))
);
console.log(
'is (new (function (){})) a derived object?',
isObject((new (function (){})))
);
// is {} an object?
console.log(
'is {} an object?', isObject({})
);
console.log(
'is {} a derived object?', isDerivedObject({})
);
// is Array an object?
console.log(
'is Array an object?',
isObject([])
)
console.log(
'is Array a derived object?',
isDerivedObject([])
)
// is Date an object?
console.log(
'is Date an object?', isObject(new Date())
);
console.log(
'is Date a derived object?', isDerivedObject(new Date())
);
// is function an object?
console.log(
'is function an object?', isObject(function(){})
);
console.log(
'is function a derived object?', isDerivedObject(function(){})
);
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-12-14 12:02:58
var a = [1]
typeof a //"object"
a instanceof Object //true
a instanceof Array //true
var b ={a: 1}
b instanceof Object //true
b instanceof Array //false
var c = null
c instanceof Object //false
c instanceof Array //false
Se me pidió que proporcionara más detalles. La forma más limpia y comprensible de comprobar si nuestra variable es un objeto es typeof myVar
. Devuelve una cadena con un tipo (por ejemplo,"object"
, "undefined"
).
Desafortunadamente, tanto Array como null también tienen un tipo object
. Para tomar solo objetos reales, es necesario verificar la cadena de herencia utilizando el operador instanceof
. Eliminará null, pero la matriz tiene un Objeto en la cadena de herencia.
Así que la solución es:
if (myVar instanceof Object && !(myVar instanceof Array)) {
// code for objects
}
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-06-10 13:16:57
Un poco tarde... para "objetos simples" (quiero decir, como {'x': 5, 'y': 7}) tengo este pequeño fragmento:
function isPlainObject(o) {
return ((o === null) || Array.isArray(o) || typeof o == 'function') ?
false
:(typeof o == 'object');
}
Genera la siguiente salida:
console.debug(isPlainObject(isPlainObject)); //function, false
console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
console.debug(isPlainObject(5)); //number, false
console.debug(isPlainObject(undefined)); //undefined, false
console.debug(isPlainObject(null)); //null, false
console.debug(isPlainObject('a')); //string, false
console.debug(isPlainObject([])); //array?, false
console.debug(isPlainObject(true)); //bool, false
console.debug(isPlainObject(false)); //bool, false
Siempre funciona para mí. If devolverá "true" solo si el tipo de " o "es " object", pero no null, or array, or function. :)
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-10-25 16:26:46
Lodash tiene isPlainObject, que podría ser lo que muchos que vienen a esta página están buscando. Devuelve false cuando se da una función o matriz.
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-10-20 19:33:23
Cuando todo lo demás falla, uso esto:
var isObject = function(item) {
return item.constructor.name === "Object";
};
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-09-18 18:42:48
Esto funcionará. Es una función que devuelve true, false o posiblemente null.
const isObject = obj => obj && obj.constructor && obj.constructor === Object;
console.log(isObject({})); // true
console.log(isObject([])); // false
console.log(isObject(new Function)); // false
console.log(isObject(new Number(123))); // false
console.log(isObject(null)); // null
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-01-05 17:49:40
Tipos de retorno
Typeof JavaScript constructores y objetos (incluyendo null
) devuelve "object"
console.log(typeof null, typeof [], typeof {})
Controlando a Sus constructores
Comprobando su propiedad constructor
devuelve la función con sus nombres.
console.log(({}).constructor) // returns a function with name "Object"
console.log(([]).constructor) // returns a function with name "Array"
console.log((null).constructor) //throws an error because null does not actually have a property
Introducción Function.name
Function.name
devuelve un nombre de solo lectura de una función o "anonymous"
para cierres.
console.log(({}).constructor.name) // returns "Object"
console.log(([]).constructor.name) // returns "Array"
console.log((null).constructor.name) //throws an error because null does not actually have a property
Final código
function isAnObject(obj)
{
if(obj==null) return false;
return obj.constructor.name.toLowerCase() === "object"
}
console.log(isAnObject({})) // return true
console.log(isAnObject([])) // returns false
console.log(isAnObject(null)) // return false
Nota: Function.name podría no funcionar en IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility
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-08-03 19:20:21
if(typeof value === 'object' && value.constructor === Object)
{
console.log("This is an object");
}
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-16 08:48:04
La biblioteca funcional Ramda tiene una función maravillosa para detectar tipos de JavaScript.
Parafraseando la función completa :
function type(val) {
return val === null ? 'Null' :
val === undefined ? 'Undefined' :
Object.prototype.toString.call(val).slice(8, -1);
}
Tuve que reírme cuando me di cuenta de lo simple y hermosa que era la solución.
Ejemplo de uso de la documentación de Ramda :
R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"
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-22 21:34:46
var isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
!!obj
es una abreviatura para comprobar si el objeto es verdadero (para filtrar null/undefined)
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-12-16 01:15:14
Lo que me gusta usar es esto
function isObject (obj) {
return typeof(obj) == "object"
&& !Array.isArray(obj)
&& obj != null
&& obj != ""
&& !(obj instanceof String) }
Creo que en la mayoría de los casos una Fecha debe pasar el cheque como un Objeto, por lo que no filtro fechas
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-24 13:19:54
He encontrado una forma "nueva" de hacer este tipo de comprobación de tipo a partir de esta pregunta SO: ¿Por qué instanceof devuelve false para algunos literales?
A partir de eso, creé una función para la comprobación de tipos de la siguiente manera:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return false; //fallback for null or undefined
}
}
Entonces puedes hacer:
console.log(isVarTypeOf('asdf', String)); // returns true
console.log(isVarTypeOf(new String('asdf'), String)); // returns true
console.log(isVarTypeOf(123, String)); // returns false
console.log(isVarTypeOf(123, Number)); // returns true
console.log(isVarTypeOf(new Date(), String)); // returns false
console.log(isVarTypeOf(new Date(), Number)); // returns false
console.log(isVarTypeOf(new Date(), Date)); // returns true
console.log(isVarTypeOf([], Object)); // returns false
console.log(isVarTypeOf([], Array)); // returns true
console.log(isVarTypeOf({}, Object)); // returns true
console.log(isVarTypeOf({}, Array)); // returns false
console.log(isVarTypeOf(null, Object)); // returns false
console.log(isVarTypeOf(undefined, Object)); // returns false
console.log(isVarTypeOf(false, Boolean)); // returns true
Esto se prueba en Chrome 56, Firefox 52, Microsoft Edge 38, Internet Explorer 11, Opera 43
Editar:
si también desea verificar si una variable es nula o indefinida, puede usar esto lugar:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
var a = undefined, b = null;
console.log(isVarTypeOf(a, undefined)) // returns true
console.log(isVarTypeOf(b, undefined)) // returns true
console.log(isVarTypeOf(a, null)) // returns true
Actualización del comentario del inanc: desafío aceptado: D
Si quieres perder objetos de comparación puedes probar de esta manera:
function isVarTypeOf(_var, _type, looseCompare){
if (!looseCompare){
try {
return _var.constructor === _type;
} catch(ex){
return _var == _type;
}
} else {
try{
switch(_var.constructor){
case Number:
case Function:
case Boolean:
case Symbol:
case Date:
case String:
case RegExp:
// add all standard objects you want to differentiate here
return _var.constructor === _type;
case Error:
case EvalError:
case RangeError:
case ReferenceError:
case SyntaxError:
case TypeError:
case URIError:
// all errors are considered the same when compared to generic Error
return (_type === Error ? Error : _var.constructor) === _type;
case Array:
case Int8Array:
case Uint8Array:
case Uint8ClampedArray:
case Int16Array:
case Uint16Array:
case Int32Array:
case Uint32Array:
case Float32Array:
case Float64Array:
// all types of array are considered the same when compared to generic Array
return (_type === Array ? Array : _var.constructor) === _type;
case Object:
default:
// the remaining are considered as custom class/object, so treat it as object when compared to generic Object
return (_type === Object ? Object : _var.constructor) === _type;
}
} catch(ex){
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
}
De esa manera, puedes hacer lo mismo que el comentario de inanc:
isVarTypeOf(new (function Foo(){}), Object); // returns false
isVarTypeOf(new (function Foo(){}), Object, true); // returns true
O
Foo = function(){};
Bar = function(){};
isVarTypeOf(new Foo(), Object); // returns false
isVarTypeOf(new Foo(), Object, true); // returns true
isVarTypeOf(new Bar(), Foo, true); // returns false
isVarTypeOf(new Bar(), Bar, true); // returns true
isVarTypeOf(new Bar(), Bar); // returns true
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 10:31:39
Dios mío, demasiada confusión en otras respuestas.
Respuesta corta
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array)
Para probar esto, simplemente ejecute las siguientes instrucciones en chrome console.
Caso 1.
var anyVar = {};
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // true
Caso 2.
anyVar = [];
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // false
Caso 3.
anyVar = null;
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array); // false
Explicación
Bien.Vamos a desglosarlo
typeof anyVar == 'object'
se devuelve true de tres candidatos - [], {} and null
,
anyVar instanceof Object
reduce estos candidatos a dos - [], {}
!(anyVar instanceof Array)
se estrecha a solo uno - {}
Redoble de tambores por favor!
Con esto puede que ya haya aprendido cómo comprobar el Array en Javascript.
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-09-24 14:20:37
Si ya está usando AngularJS, entonces tiene un método incorporado que comprobará si es un objeto (sin aceptar null).
angular.isObject(...)
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-05-20 11:34:08
Use typeof(my_obj)
le dirá qué tipo de variable es.
Si es objeto de mostrar 'objeto'
Función JS simple,
function isObj(v) {
return typeof(v) == "object"
}
Eg:
function isObj(v) {
return typeof(v) == "object"
}
var samp_obj = {
"a" : 1,
"b" : 2,
"c" : 3
}
var num = 10;
var txt = "Hello World!"
var_collection = [samp_obj, num, txt]
for (var i in var_collection) {
if(isObj(var_collection[i])) {
console.log("yes it is object")
}
else {
console.log("No it is "+ typeof(var_collection[i]))
}
}
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-07-19 06:48:10
Depende del caso de uso, si no queremos permitir que la matriz y las funciones sean un Objeto, podemos usar el subrayado.funciones incorporadas de js.
function xyz (obj) {
if (_.isObject(obj) && !_.isFunction(obj) && !.isArray(obj)) {
// now its sure that obj is an object
}
}
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-11-12 11:11:23
Se usa principalmente typeof obj[index] === 'object'
, pero también devolverá function
y #document
que son objetos. Depende de usted si necesita ser incluido en el resultado.
Básicamente puede hacer un código de prueba que filtre si un elemento en particular es un objeto comprobando la salida en su consola. Aquí puede ejecutar un código solo para una muestra:
function cekObject(obj, index) {
if (!obj.tagName) {
//test case #1
if (typeof obj === 'object') {
console.log('obj['+ index +'] is listed as an object');
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<script>
function updateFilters() {
var object = $('.j-image');
$('.juicer-feed').empty();
for(var index in object) {
cekObject(object[index], index);
};
}
</script>
<ul class="juicer-feed" data-feed-id="chetabahana" data-after="updateFilters()"></ul>
<script src="https://assets.juicer.io/embed.js"></script>
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-23 01:57:00
Si desea comprobar si el prototype
un object
únicamente proviene de Object
. Filtros hacia fuera String
, Number
, Array
, Arguments
, etc.
function isObject(n) {
if (n == null) return false;
return Object.prototype.toString.call(n) === '[object Object]';
}
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-06-13 11:19:57