如何检查值是否是JavaScript中的对象?


当前回答

这会奏效的。它是一个返回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));//无效的

其他回答

我喜欢简单地:

function isObject (item) {
  return (typeof item === "object" && !Array.isArray(item) && item !== null);
}

如果该项是一个JS对象,并且它不是一个JS数组,并且它不为空……如果这三个都是真的,则返回true。如果三个条件中的任何一个失败,&&测试将短路,并返回false。如果需要,可以省略null测试(取决于如何使用null)。

文档:

http://devdocs.io/javascript/operators/typeof

http://devdocs.io/javascript/global_objects/object

http://devdocs.io/javascript/global_objects/array/isarray

http://devdocs.io/javascript/global_objects/null

underscore.js提供了以下方法来确定某个对象是否真的是对象:

_.isObject = function(obj) {
  return obj === Object(obj);
};

更新

由于V8之前的一个bug和轻微的微速度优化,自underscore.js 1.7.0(2014年8月)以来,该方法如下:

_.isObject = function(obj) {
  var type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
};

简单的工作解决方案:

function isObject(value) {
    return !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}

出于代码的目的,我找到了与上面的一些答案相对应的决定:

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

等等

我的上帝,其他答案太混乱了。

简短回答

typeof anyVar==“对象”&&anyVar对象实例&&!(数组的anyVar实例)

要测试这一点,只需在chrome控制台中运行以下语句。

案例1。

var anyVar = {};
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // true

案例2。

anyVar = [];
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // false

案例3。

anyVar = null;
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array); // false

解释

好吧,我们来分解一下

typeof anyVar==“object”从三个候选项中返回true-[]、{}和null,

anyVar instanceof Object将这些候选对象缩小到两个-[],{}

!(anyVar instanceof Array)仅限于一个-{}

请滚鼓!

至此,您可能已经学会了如何在Javascript中检查Array。