如何检查值是否是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();
}

其他回答

Ramda函数库具有检测JavaScript类型的出色功能。

完整功能的释义:

function type(val) {
  return val === null      ? 'Null'      :
         val === undefined ? 'Undefined' :
         Object.prototype.toString.call(val).slice(8, -1);
}

当我意识到解决方案是多么简单和美丽时,我不得不笑了。

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"

这会奏效的。它是一个返回true、false或可能为null的函数。

const isObject=obj=>obj&&obj.constructor&&obj.structor==对象;console.log(isObject({}));//真的console.log(isObject([]));//假的console.log(isObject(新函数));//假的console.log(isObject(新编号(123)));//假的console.log(isObject(null));//无效的

这取决于用例,如果我们不想让数组和函数成为Object,我们可以使用undercore.js内置函数。

    function xyz (obj) { 
       if (_.isObject(obj) && !_.isFunction(obj) && !_.isArray(obj)) {
         // now its sure that obj is an object 
       } 
    }

如果您想检查对象的原型是否仅来自object。过滤掉字符串、数字、数组、参数等。

function isObject (n) {
  return Object.prototype.toString.call(n) === '[object Object]';
}

或作为单个表达式箭头函数(ES6+)

const isObject = n => Object.prototype.toString.call(n) === '[object Object]'

您可以使用JSON.stringify来测试Object,如下所示:

var测试={}if(JSON.stringify(测试)[0]==“{”){console.log('这是一个对象')}