如何检查值是否是JavaScript中的对象?
当前回答
您可以使用Object.prototype的toString()方法轻松完成此操作
if(Object.prototype.toString.call(variable) == "[object Object]"){
doSomething();
}
or
if(Object.prototype.toString.call(variable).slice(8,-1).toLowerCase() == "object"){
doSomething();
}
其他回答
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
const isObject = function(obj) {
const type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
!!obj是检查obj是否正确(以过滤空值)的简写
我喜欢用这个
function isObject (obj) {
return typeof(obj) == "object"
&& !Array.isArray(obj)
&& obj != null
&& obj != ""
&& !(obj instanceof String) }
我认为在大多数情况下,Date必须作为Object通过检查,因此我不会过滤掉日期
您可以使用Object.prototype的toString()方法轻松完成此操作
if(Object.prototype.toString.call(variable) == "[object Object]"){
doSomething();
}
or
if(Object.prototype.toString.call(variable).slice(8,-1).toLowerCase() == "object"){
doSomething();
}
function isObjectLike(value) {
return value != null && typeof value == 'object' && !Array.isArray(value);
}
基于lodash