如何检查值是否是JavaScript中的对象?
当前回答
当其他一切都失败时,我使用这个:
var isObject = function(item) {
return item.constructor.name === "Object";
};
其他回答
如果您已经在使用AngularJS,那么它有一个内置的方法,可以检查它是否是一个对象(不接受null)。
angular.isObject(...)
出于代码的目的,我找到了与上面的一些答案相对应的决定:
ES6变体:
const checkType = o => Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
ES5变体:
function checkType(o){
return Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
}
您可以非常简单地使用它:
checkType([]) === 'array'; // true
checkType({}) === 'object'; // true
checkType(1) === 'number'; // true
checkType('') === 'string'; // true
checkType({}.p) === 'undefined'; // true
checkType(null) === 'null'; // true
等等
简单的工作解决方案:
function isObject(value) {
return !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}
if(typeof value === 'object' && value.constructor === Object)
{
console.log("This is an object");
}
当其他一切都失败时,我使用这个:
var isObject = function(item) {
return item.constructor.name === "Object";
};