检查一个值是否是JavaScript中的一个对象
你如何检查一个值是否是JavaScript中的对象?
 尝试使用typeof(var)和/或var instanceof something 。 
编辑:这个答案给出了如何检查variables的属性,但它不是一个防弹食谱(毕竟没有食谱!)检查是否是一个对象,远离它。 由于人们往往在没有做任何研究的情况下寻找要复制的东西,所以我强烈build议他们转向另一个,最上面的(而且是正确的)答案。
 如果typeof yourVariable === 'object' ,它是一个对象或null。 如果你想排除null,只需使它yourVariable !== null && typeof yourVariable === 'object'你的yourVariable !== null && typeof yourVariable === 'object' 。 
让我们在Javascript中定义“对象” 。 根据MDN文档 ,每个值都是对象或基元:
原始的,原始的价值
不是对象的数据,也没有任何方法。 JavaScript有5种基本数据types:string,数字,布尔值,空值,未定义。
什么是原始的?
-  3
-  'abc'
-  true
-  null
-  undefined
什么是对象(即不是原始的)?
-  Object.prototype
-  所有东西都来自Object.prototype-  Function.prototype-  Object
-  Function
-   function C(){}– 用户定义的函数
 
-  
-   C.prototype– 用户定义函数的原型属性:这不是C的原型-   new C()– “新” – 用户定义的函数
 
-   
-  Math
-  Array.prototype- arrays
 
-   {"a": 1, "b": 2}– 使用文字符号创build的对象
-   new Number(3)– 原语的包装
- … 许多其他的事情 …
 
-  
-  Object.create(null)
-  一切从一个Object.create(null)
如何检查一个值是否是一个对象
  instanceof本身是行不通的,因为它错过了两种情况: 
 // oops: isObject(Object.prototype) -> false // oops: isObject(Object.create(null)) -> false function isObject(val) { return val instanceof Object; } 
  typeof x === 'object'将不起作用,因为误报( null )和漏报(函数): 
 // oops: isObject(Object) -> false function isObject(val) { return (typeof val === 'object'); } 
  Object.prototype.toString.call将不起作用,因为所有原语的误报: 
 > Object.prototype.toString.call(3) "[object Number]" > Object.prototype.toString.call(new Number(3)) "[object Number]" 
所以我使用:
 function isObject(val) { if (val === null) { return false;} return ( (typeof val === 'function') || (typeof val === 'object') ); } 
大安的答案似乎也起作用:
 function isObject(obj) { return obj === Object(obj); } 
因为根据MDN文档 :
Object构造函数为给定的值创build一个对象包装器。 如果该值为null或未定义,它将创build并返回一个空对象,否则它将返回与给定值相对应的types的对象。 如果该值已经是一个对象,它将返回该值。
 似乎工作的第三种方法(不知道它是否是100%)是使用Object.getPrototypeOf ,如果它的参数不是一个对象,则引发exception : 
 // 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({}) 
官方的underscore.js使用这个检查来找出是否真的是一个对象
 // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; 
  Object.prototype.toString.call(myVar)将返回: 
-   "[object Object]"如果myVar是一个对象
-   "[object Array]"如果myVar是一个数组
- 等等
有关这方面的更多信息,以及为什么它是typeof的一个很好的select, 请参阅这篇文章 。
我喜欢简单:
 function isObject (item) { return (typeof item === "object" && !Array.isArray(item) && item !== null); } 
 如果该项目是一个JS对象,它不是一个JS数组,它不为null …如果三个都certificate是真的,则返回true 。 如果三个条件中的任何一个失败, &&testing将会短路并返回false 。 如果需要,可以省略nulltesting(取决于你如何使用null )。 
DOCS:
http://devdocs.io/javascript/operators/typeof
http://devdocs.io/javascript/global_objects/object
只需检查对象或数组,而无需额外的函数调用(速度)。 也发布在这里 。
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() – 注意:仅用于Object文字,因为它会为自定义对象返回false,如新的Date或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 
好的,让我们首先给你这个概念,然后回答你的问题,在JavaScript函数是对象,空,对象,数组和甚至date,所以你看它不是简单的方式像typeof obj ==='对象',所以提到的一切上面将返回true,但有办法检查它与编写一个函数或使用JavaScript框架,行:
现在,假设你有这个对象是一个真实的对象(不是null或函数或数组):
 var obj = {obj1: 'obj1', obj2: 'obj2'}; 
纯粹的JavaScript:
 //that's how it gets checked in angular framework function isObject(obj) { return obj !== null && typeof obj === 'object'; } 
要么
 //make sure the second object is capitalised function isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } 
要么
 function isObject(obj) { return obj.constructor.toString().indexOf("Object") > -1; } 
要么
 function isObject(obj) { return obj instanceof Object; } 
你可以通过调用它们在代码中简单地使用上面这些函数中的一个,如果它是一个对象,它将返回true:
 isObject(obj); 
如果你正在使用JavaScript框架,他们通常为你准备了这些function,这些function很less:
jQuery的:
  //It returns 'object' if real Object; jQuery.type(obj); 
angular度:
 angular.isObject(obj); 
下划线和Lodash:
 //(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null) _.isObject(obj); 
这取决于你的意思是“是一个对象”。 如果你想要的东西不是一个原始的东西,即你可以设置新的属性的东西,这应该做的伎俩:
 function isAnyObject(value) { return value != null && (typeof value === 'object' || typeof value === 'function'); } 
 它排除了原始数据(普通数字/ NaN / Infinity ,纯string, true / false , undefined和null ),但是对于其他所有数据(包括Number , Boolean和String对象)都应该返回true。 请注意,JS没有定义什么“主机”对象,如window或console ,应该返回与typeof使用时,所以这些都很难用这样的检查来覆盖。 
 如果你想知道某个东西是否是一个“简单的”对象,也就是说,它是作为一个文字创build的,还是与Object.create(null) ,你可以这样做: 
 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; } } 
 检查一个值的types的最合理的方法似乎是typeof运算符。 唯一的问题是,它是可怕的破碎: 
-  它返回null"object",它属于空types。
-  它为属于Objecttypes的可调用对象返回"function"。
-  它可以返回(几乎)任何它想要的非标准非可调用对象。 例如,IE似乎喜欢"unknown"。 唯一禁止的结果是"function"和原始types。
  typeof只对非null原语可靠。 所以一个检查一个值是否是对象的方法是确保typeof返回的string不对应于一个原语,并且该对象不是null 。 但是,问题是未来的标准可能会引入一个新的基本types,我们的代码会认为它是一个对象。 新types不经常出现,但是例如ECMAScript 6引入了符号types。 
 因此,我只推荐其结果取决于值是否是对象的方法,而不是typeof 。 以下打算成为一个 
全面但并不完整的testing值是否属于对象types的正确方法列表。
- 
Object构造函数Object构造函数将传递的参数强制转换为对象。 如果它已经是一个对象,则返回相同的对象。因此,您可以使用它将值强制转换为对象,并严格将该对象与原始值进行比较。 下面的函数需要ECMAScript 3,它引入了 ===:function isObject(value) { /* Requires ECMAScript 3 or later */ return Object(value) === value; }我喜欢这种方法,因为它很简单,自我描述,类似的检查也适用于布尔值,数字和string。 但是,请注意,它依赖于全局 Object不被遮挡或更改。
- 
构造函数 当你实例化一个构造函数时,它可以返回一个不同于刚刚创build的实例的值。 但是这个价值将被忽略,除非它是一个对象。 下面的函数需要ECMAScript 3,它允许构造函数返回非对象。 在ECMAScript 3之前抛出一个错误,但是 try语句并不存在。function isObject(value) { /* Requires ECMAScript 3 or later */ return new function() { return value; }() === value; }虽然比前面的例子简单一点,但是这个不依赖任何全局属性,因此可能是最安全的。 
- 
this值旧的ECMAScript规范要求 this值是一个对象。 ECMAScript 3引入了Function.prototype.call,它允许用一个任意的this值调用一个函数,但是强制转换成一个对象。ECMAScript 5引入了一个严格的模式来消除这种行为,但是在马虎模式下,我们仍然可以(但可以说不应该)依赖它。 function isObject(value) { /* Requires ECMAScript 3 or later in sloppy mode */ return function() { return this === value; }.call(value); }
- 
[[原型]] 所有的普通对象都有一个名为[[Prototype]]的内部槽,它的值决定了从哪个其他对象inheritance而来。 该值只能是一个对象或 null。 因此,您可以尝试创build一个从所需值inheritance的对象,并检查它是否工作。Object.create和Object.getPrototypeOf都需要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; }
- 
一些新的ECMAScript 6方法 ECMAScript 6引入了一些新的间接方法来检查一个值是否是一个对象。 他们使用先前看到的方法将值传递给需要一个对象的代码,包装在一个 try语句中以捕获错误。 一些隐藏的例子,不值得评论function isObject(value) { /* Requires ECMAScript 6 or later */ try { Object.setPrototypeOf({}, value); return value !== null; } catch(err) { return false; } }
准备使用function进行检查
 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 
说明
- 
在Javascript中, null,Object,Array,Date和function都是对象。 虽然,null是有点人为的。 所以,最好首先检查null,检测它不是null。
- 
检查 typeof o === 'object'确保o是一个对象。 没有这个检查,Object.prototype.toString将是无意义的,因为它将返回对象的外挂,即使对于undefined和null! 例如:toString(undefined)返回[object Undefined]!在 typeof o === 'object'检查之后,toString.call(o)是一个很好的方法来检查o是否是一个对象,派生的对象如Array,Date或者function。
- 
在 isDerivedObject函数中,它检查o是一个函数。 因为,function也是一个对象,这就是为什么它在那里。 如果不这样做,函数将返回false。 示例:isDerivedObject(function() {})将返回false,但现在它返回true。
- 
人们总是可以改变什么是对象的定义。 所以,可以相应地改变这些function。 
testing
 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(){}) ); 
对于“简单的对象”(我的意思是,像{'x':5,'y':7}),我有这个小片段:
 function isPlainObject(o) { return ((o === null) || Array.isArray(o) || typeof o == 'function') ? false :(typeof o == 'object'); } 
它生成下一个输出:
 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 
它总是为我工作。 如果仅当“o”的types是“object”,而不是null或数组或函数时才返回“true”。 🙂
 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 
 我被要求提供更多细节。 检查我们的variables是否是一个对象的最干净和可以理解的方式是typeof myVar 。 它返回一个types的string(例如"object" , "undefined" )。 
 不幸的是,Array和null也有一个typesobject 。 只接受真实对象需要使用instanceof运算符来检查inheritance链。 它将消除null,但Array具有inheritance链中的Object。 
所以解决办法是:
 if (myVar instanceof Object && !(myVar instanceof Array)) { // code for objects } 
 只是惊讶有多less错误的答案up 
 只有1个答案通过了我的testing! 在这里我创build了我的简化版本: 
 function isObject(o) { return o instanceof Object && o.constructor === Object; } 
至于我,它很清楚,简单,只是工作! 在这里我的testing:
 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 
再一次:不是所有的答案都通过这个testing! 🙈
如果你需要validation对象是特定类的实例,你必须检查你的特定类的构造函数,如:
 function isDate(o) { return o instanceof Object && o.constructor === Date; } 
简单testing:
 var d = new Date(); console.log(isObject(d)); // Will return: false console.log(isDate(d)); // Will return: true 
因此,你将有严格和健壮的代码!
尝试这个
 if (objectName instanceof Object == false) { alert('Not an object'); } else { alert('An object'); } 
当一切都失败了,我用这个:
 var isObject = function(item) { return item.constructor.name === "Object"; }; 
lodash有isPlainObject ,这可能是许多来到这个页面的人正在寻找。 给一个函数或数组时它返回false。
  var isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; 
  !!obj是检查对象是否真的简写(过滤掉null / undefined) 
我认为这将工作。 返回true或false的函数,可能为null。
 const isObject = obj => obj && obj.constructor && obj.constructor === Object; isObject({}) // true isObject([]) // false isObject(new Number(123)) // false isObject(null) // null 
如果你已经使用AngularJS,那么它有一个内置的方法,将检查它的一个对象(不接受空)。
 angular.isObject(...) 
我喜欢使用的是这个
 function isObject (obj) { return typeof(obj) == "object" && !Array.isArray(obj) && obj != null && obj != "" && !(obj instanceof String) } 
我认为在大多数情况下,date必须通过支票作为对象,所以我不会过滤date
i found a "new" way to do just this kind of type checking from this SO question: Why does instanceof return false for some literals?
from that, i created a function for type checking as follows:
 function isVarTypeOf(_var, _type){ try { return _var.constructor === _type; } catch(ex) { return false; //fallback for null or undefined } } 
then you can just do:
 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 
this is tested on Chrome 56, Firefox 52, Microsoft Edge 38, Internet Explorer 11, Opera 43
  编辑: 
 if you also want to check if a variable is null or undefined, you can use this instead: 
 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 
update from inanc's comment: challenge accepted 😀
if you want to loose compare objects you can try this way:
 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 } } } 
that way, you can do just like inanc's comment:
 isVarTypeOf(new (function Foo(){}), Object); // returns false isVarTypeOf(new (function Foo(){}), Object, true); // returns true 
要么
 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 
 use typeof(my_obj) will tells which type of variable it is. 
if it is object will show 'object'
simple JS function,
 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])) } } 
Its depends on use-case, if we do not want to allow array and functions to be an Object, we can use the underscore.js builtin functions.
 function xyz (obj) { if (_.isObject(obj) && !_.isFunction(obj) && !.isArray(obj)) { // now its sure that obj is an object } } 
 var isArray=function(value){ if(Array.isArray){ return Array.isArray(value); }else{ return Object.prototype.toString.call(value)==='[object Array]'; } } var isObject=function(value){ return value !== null&&!isArray(value) && typeof value === 'object'; } var _val=new Date; console.log(isObject(_val));//true console.log(Object.prototype.toString.call(_val)==='[object Object]');//false 
You can do this easily with toString() method of Object.prototype
 if(Object.prototype.toString.call(variable) == "[object Object]"){ doSomething(); } 
要么
 if(Object.prototype.toString.call(variable).slice(8,-1).toLowerCase() == "object"){ doSomething(); } 
 A little NodeJS console experiment based on the reading of Matt Fenwick's third option to his complete answer above. Just a little tweak to get true or false . 
The following return false for the object test.
 > if(Object.getPrototypeOf('v') === Object.prototype){console.log(true);}else{console.log(false);} false undefined > if(Object.getPrototypeOf(1) === Object.prototype){console.log(true);}else{console.log(false);} false undefined > if(Object.getPrototypeOf(false) === Object.prototype){console.log(true);}else{console.log(false);} false undefined > if(Object.getPrototypeOf(['apple']) === Object.prototype){console.log(true);}else{console.log(false);} false undefined 
The object will return true.
 > if(Object.getPrototypeOf({'this':10}) === Object.prototype){console.log(true);}else{console.log(false);} true undefined 
 direct answer is ofcourse typeof v==='object' but this is terribly not useful. I wonder if the OP meant a plain dictionary .. 
尝试:
 isdict(v) { return v !== undefined && v!==null && typeof v==='object' && v.constructor!==Array && v.constructor!==Date; } 
I have a code snippet that works. I find it confusing when the whole piece of code is not given, so I just created it myself:
  <!DOCTYPE html> <html> <body> <button onclick="myFunc()">Try it</button> <script> var abc = new Number(); // var abc = 4; //this is a code variation which will give a diff alert function myFunc() { if(abc && typeof abc === "object") alert('abc is an object and does not return null value'); else alert('abc is not an object'); } </script> </body> </html>