<!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');elsealert('abc is not an object');}</script>
</body></html>
function isPlainObject(o) {return (o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ) ?false:(typeof o == '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));//trueconsole.log(Object.prototype.toString.call(_val)==='[object Object]');//false
var a = [1]typeof a //"object"a instanceof Object //truea instanceof Array //true
var b ={a: 1}b instanceof Object //trueb instanceof Array //false
var c = nullc instanceof Object //falsec instanceof Array //false
function isObject(value) { /* Requires ECMAScript 3 or later in sloppy mode */return function() { return this === value; }.call(value);}
[[Prototype]]
All ordinary objects have an internal slot called [[Prototype]], whose value determines from which other object it inherits from. The value can only be an object or null. Therefore, you can attempt to create an object which inherits from the desired value, and check if it worked.
Both Object.create and Object.getPrototypeOf require 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;}
Some new ECMAScript 6 ways
ECMAScript 6 introduces some new indirect ways to check is a value is an object. They use the previously seen approach to pass the value to some code which requires an object, wrapped inside a try statement to catch errors. Some hidden examples, not worth commenting
function 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;}}
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
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(){}));
这在Chrome56,Firefox 52,Microsoft Edge38,Internet Explorer 11,Opera 43上进行了测试
编辑: 如果您还想检查变量是否为空或未定义,您可以改为使用:
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 trueconsole.log(isVarTypeOf(b, undefined)) // returns trueconsole.log(isVarTypeOf(a, null)) // returns true
来自inanc评论的更新:接受挑战:D
如果你想失去比较对象,你可以尝试这种方式:
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 herereturn _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 Errorreturn (_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 Arrayreturn (_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 Objectreturn (_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}}}
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]))}}
function isObject(o) {return o instanceof Object && o.constructor === Object;}
至于我,它是清晰和简单的,只是工作!这是我的测试:
console.log(isObject({})); // Will return: trueconsole.log(isObject([])); // Will return: falseconsole.log(isObject(null)); // Will return: falseconsole.log(isObject(/.*/)); // Will return: falseconsole.log(isObject(function () {})); // Will return: false
再一次:不是所有的答案都能通过这个测试!!!🙈
如果您需要验证该对象是否为特定类的实例,则必须使用您的特定类检查构造函数,例如:
function isDate(o) {return o instanceof Object && o.constructor === Date;}
简单测试:
var d = new Date();console.log(isObject(d)); // Will return: falseconsole.log(isDate(d)); // Will return: true
因此,您将拥有严格而健壮的代码!
如果您不创建isDate、isError、isRegExp等函数,您可以考虑使用此通用函数的选项:
function isObject(o) {return o instanceof Object && typeof o.constructor === 'function';}
function cekObject(obj, index) {if (!obj.tagName) {
//test case #1if (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>
Checking on their constructor property returns function with their names.
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
介绍Function.name
Function.name返回函数的只读名称,"anonymous"返回闭包。
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
<scriptsrc="https://code.jquery.com/jquery-3.5.1.min.js"integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="crossorigin="anonymous"></script>
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww=="crossorigin="anonymous"></script>
This shippet only presents functions used in performance tests - it not perform tests itself!
function typeOfIs(val, type) {return typeof val == type;}
function constructorIs(val, constructor) {return val && constructor && val.constructor === constructor;}
function isObject(val) {// catch the easy non-object valuesif (!typeOfIs(val, 'object'))return false;
// catch the cases you don't want to consider to be// "real" objects for your use-caseswitch (true) {case val === null:case Array.isArray(val):case typeOfIs(val, 'function'):case constructorIs(val, RegExp):return false;default:return true;}}function test(val) {console.log(Object.prototype.toString.call(val)+': '+isObject(val));}test(undefined);test(null);test(function () {});test(Symbol('foo'));test(1);test(true);test(false);test('hello world');test([]);test(/.*/g);test(new Date()); // true (because we didn't filter for it)test({}); // true