检查一个值是否是 JavaScript 中的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8511281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:19:28  来源:igfitidea点击:

Check if a value is an object in JavaScript

javascriptobjecttypesjavascript-objects

提问by Danny Fox

How do you check if a value is an Object in JavaScript?

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

采纳答案by Michael Krelin - hacker

UPDATE:

更新

This answer is incomplete and gives misleading results. For example, nullis also considered of type objectin JavaScript, not to mention several other edge cases. Follow the recommendation below and move on to other "most upvoted (and correct!) answer".

这个答案是不完整的,并给出了误导性的结果。例如,在 JavaScript 中null也被认为是类型object,更不用说其他几个边缘情况了。遵循下面的建议,然后转到其他“最受好评(和正确!)答案”



Original answer:

原答案

Try using typeof(var)and/or var instanceof something.

尝试使用typeof(var)和/或var instanceof something.

EDIT: This answer gives an idea of how to examine variable's properties, but it is nota bulletproof recipe (after all there's no recipe at all!) for checking whether it's an object, far from it. Since people tend to look for something to copy from here without doing any research, I'd highly recommend that they turn to the other, most upvoted (and correct!) answer.

编辑:这个答案给出了如何检查变量属性的想法,但它不是一个防弹配方(毕竟根本没有配方!)来检查它是否是一个远离它的对象。由于人们倾向于在不做任何研究的情况下从这里寻找可以复制的东西,我强烈建议他们转向另一个最受好评(并且正确!)的答案。

回答by Chuck

If typeof yourVariable === 'object', it's an object or null. If you want to exclude null, just make it typeof yourVariable === 'object' && yourVariable !== null.

如果typeof yourVariable === 'object',它是一个对象或为空。如果你想排除 null,就让它typeof yourVariable === 'object' && yourVariable !== null.

回答by Matt Fenwick

Let's define "object" in Javascript. According to the MDN docs, every value is either an object or a primitive:

让我们在 Javascript 中定义“对象”。根据MDN 文档,每个值要么是对象,要么是原语:

primitive, primitive value

A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined.

原始值,原始值

不是对象且没有任何方法的数据。JavaScript 有 5 种原始数据类型:字符串、数字、布尔值、空值、未定义。

What's a primitive?

什么是原始人?

  • 3
  • 'abc'
  • true
  • null
  • undefined
  • 3
  • 'abc'
  • true
  • null
  • undefined

What's an object (i.e. not a primitive)?

什么是对象(即不是原始对象)?

  • Object.prototype
  • everything descended from Object.prototype
    • Function.prototype
      • Object
      • Function
      • function C(){}-- user-defined functions
    • C.prototype-- the prototype property of a user-defined function: this is notCs prototype
      • new C()-- "new"-ing a user-defined function
    • Math
    • Array.prototype
      • arrays
    • {"a": 1, "b": 2}-- objects created using literal notation
    • new Number(3)-- wrappers around primitives
    • ... many other things...
  • Object.create(null)
  • everything descended from an Object.create(null)
  • Object.prototype
  • 一切都源于 Object.prototype
    • Function.prototype
      • Object
      • Function
      • function C(){}-- 用户自定义函数
    • C.prototype-- 用户定义函数的原型属性:这不是C原型
      • new C()-- "new"-ing 一个用户定义的函数
    • Math
    • Array.prototype
      • 数组
    • {"a": 1, "b": 2}-- 使用文字符号创建的对象
    • new Number(3)-- 原语的包装器
    • ......许多其他事情......
  • Object.create(null)
  • 一切都源于 Object.create(null)

How to check whether a value is an object

如何检查一个值是否是一个对象

instanceofby itself won't work, because it misses two cases:

instanceof本身不起作用,因为它错过了两种情况:

// oops:  isObject(Object.prototype) -> false
// oops:  isObject(Object.create(null)) -> false
function isObject(val) {
    return val instanceof Object; 
}

typeof x === 'object'won't work, because of false positives (null) and false negatives (functions):

typeof x === 'object'将不起作用,因为误报 ( null) 和漏报(函数):

// oops: isObject(Object) -> false
function isObject(val) {
    return (typeof val === 'object');
}

Object.prototype.toString.callwon't work, because of false positives for all of the primitives:

Object.prototype.toString.call不会工作,因为所有原语的误报:

> Object.prototype.toString.call(3)
"[object Number]"

> Object.prototype.toString.call(new Number(3))
"[object Number]"

So I use:

所以我使用:

function isObject(val) {
    if (val === null) { return false;}
    return ( (typeof val === 'function') || (typeof val === 'object') );
}


@Daan's answer also seems to work:

@Daan 的回答似乎也有效:

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

because, according to the MDN docs:

因为,根据MDN 文档

The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a type that corresponds to the given value. If the value is an object already, it will return the value.

Object 构造函数为给定值创建一个对象包装器。如果值为 null 或 undefined,它将创建并返回一个空对象,否则,它将返回一个与给定值对应的类型的对象。如果该值已经是一个对象,它将返回该值。



A third way that seems to work (not sure if it's 100%) is to use Object.getPrototypeOfwhich throws an exceptionif its argument isn't an object:

第三种似乎有效的方法(不确定是否为 100%)是使用Object.getPrototypeOfwhich如果其参数不是对象则抛出异常

// these 5 examples throw exceptions
Object.getPrototypeOf(null)
Object.getPrototypeOf(undefined)
Object.getPrototypeOf(3)
Object.getPrototypeOf('abc')
Object.getPrototypeOf(true)

// these 5 examples don't throw exceptions
Object.getPrototypeOf(Object)
Object.getPrototypeOf(Object.prototype)
Object.getPrototypeOf(Object.create(null))
Object.getPrototypeOf([])
Object.getPrototypeOf({})

回答by Daan

underscore.jsprovides the following method to find out if something is really an object:

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

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

UPDATE

更新

Because of a previous bug in V8 and minor micro speed optimization, the method looks as follows since underscore.js 1.7.0(August 2014):

由于先前 V8 中的错误和微小的微速度优化,自underscore.js 1.7.0(2014 年 8 月)以来,该方法如下所示:

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

回答by Christophe

Object.prototype.toString.call(myVar)will return:

Object.prototype.toString.call(myVar)将返回:

  • "[object Object]"if myVar is an object
  • "[object Array]"if myVar is an array
  • etc.
  • "[object Object]"如果 myVar 是一个对象
  • "[object Array]"如果 myVar 是一个数组
  • 等等。

For more information on this and why it is a good alternative to typeof, check out this article.

有关这方面的更多信息以及为什么它是 typeof 的一个很好的替代品,请查看这篇文章

回答by zupa

For simply checking against Object or Array without additional function call (speed). As also posted here.

用于简单地检查对象或数组而无需额外的函数调用(速度)。因为也贴在这里

isArray()

isArray()

isArray = function(a) {
    return (!!a) && (a.constructor === Array);
};
console.log(isArray(        )); // false
console.log(isArray(    null)); // false
console.log(isArray(    true)); // false
console.log(isArray(       1)); // false
console.log(isArray(   'str')); // false
console.log(isArray(      {})); // false
console.log(isArray(new Date)); // false
console.log(isArray(      [])); // true

isObject()- Note: use for Object literals only, as it returns false for custom objects, like new Date or new YourCustomObject.

isObject()- 注意:仅用于对象文字,因为它为自定义对象返回 false,例如 new Date 或 new YourCustomObject。

isObject = function(a) {
    return (!!a) && (a.constructor === Object);
};
console.log(isObject(        )); // false
console.log(isObject(    null)); // false
console.log(isObject(    true)); // false
console.log(isObject(       1)); // false
console.log(isObject(   'str')); // false
console.log(isObject(      [])); // false
console.log(isObject(new Date)); // false
console.log(isObject(      {})); // true

回答by 2540625

I'm fond of simply:

我喜欢简单:

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

If the item is a JS object, and it's not a JS array, and it's not null…if all three prove true, return true. If any of the three conditions fails, the &&test will short-circuit and falsewill be returned. The nulltest can be omitted if desired (depending on how you use null).

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

DOCS:

文件:

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

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

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

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

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

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

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

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

回答by V. Kovpak

With function Array.isArray:

功能Array.isArray

function isObject(o) {
  return o !== null && typeof o === 'object' && Array.isArray(o) === false;
}

Without function Array.isArray:

没有功能Array.isArray

Just surprised how many upvotes for wrong answers
Only 1 answerpassed my tests!!! Here I've created my simplified version:

只是惊讶有多少人为错误答案点赞
只有1 个答案通过了我的测试!!!在这里,我创建了我的简化版本:

function isObject(o) {
  return o instanceof Object && o.constructor === Object;
}

As for me, it's clear and simple, and just works! Here my tests:

对我来说,它简单明了,而且很管用!这是我的测试:

console.log(isObject({}));             // Will return: true
console.log(isObject([]));             // Will return: false
console.log(isObject(null));           // Will return: false
console.log(isObject(/.*/));           // Will return: false
console.log(isObject(function () {})); // Will return: false

ONE MORE TIME: not all answers pass this tests !!!

再一次:并非所有答案都通过了此测试!!!



In case you need to verify that object is instance of particular classyou have to check constructor with your particular class, like:

如果您需要验证对象是特定类的实例,则必须使用特定类检查构造函数,例如:

function isDate(o) {
  return o instanceof Object && o.constructor === Date;
}

simple test:

简单测试:

var d = new Date();
console.log(isObject(d)); // Will return: false
console.log(isDate(d));   // Will return: true

As result, you will have strict and robust code!

结果,您将拥有严格而健壮的代码!



In case you won't create functions like isDate, isError, isRegExp, etc you may consider option to use this generalized functions:

如果您不创建, , 等函数isDate,您可以考虑选择使用此通用函数:isErrorisRegExp

function isObject(o) {
  return o instanceof Object && typeof o.constructor === 'function';
}

it won't work correctly for all test cases mentioned earlier, but it's good enough for all objects (plain or constructed).

对于前面提到的所有测试用例,它无法正常工作,但对于所有对象(普通对象或构造对象)来说已经足够了。



isObjectwon't work in case of Object.create(null)because of internal implementation of Object.createwhich is explained herebut you can use isObjectin more sophisticated implementation:

isObject将无法工作,Object.create(null)因为这里Object.create解释了内部实现,但您可以在更复杂的实现中使用:isObject

function isObject(o, strict = true) {
  if (o === null || o === undefined) {
    return false;
  }
  const instanceOfObject = o instanceof Object;
  const typeOfObject = typeof o === 'object';
  const constructorUndefined = o.constructor === undefined;
  const constructorObject = o.constructor === Object;
  const typeOfConstructorObject = typeof o.constructor === 'function';
  let r;
  if (strict === true) {
    r = (instanceOfObject || typeOfObject) && (constructorUndefined || constructorObject);
  } else {
    r = (constructorUndefined || typeOfConstructorObject);
  }
  return r;
};

There is already created package on npmv1 based on this implementation! And it works for all earlier described test cases!

已经基于这个实现在 npmv1 上创建了!它适用于所有前面描述的测试用例!

回答by Erisan Olasheni

Oh My God! I think this could be more shorter than ever, let see this:

我的天啊!我认为这可能比以往任何时候都更短,让我们看看:

Short and Final code

简短和最终代码

function isObject(obj)
{
    return obj != null && obj.constructor.name === "Object"
}

console.log(isObject({})) // returns true
console.log(isObject([])) // returns false
console.log(isObject(null)) // returns false

Explained

解释

Return Types

返回类型

typeof JavaScript objects (including null) returns "object"

typeof JavaScript 对象(包括null)返回"object"

console.log(typeof null, typeof [], typeof {})

Checking on Their constructors

检查他们的构造函数

Checking on their constructorproperty returns function with their names.

检查他们的constructor属性会返回带有他们名字的函数。

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

Introducing Function.name

介绍 Function.name

Function.namereturns a readonly name of a function or "anonymous"for closures.

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

Note:As of 2018, Function.name might not work in IEhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility

注意:截至 2018 年,Function.name 可能无法在IE 中使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility

回答by Alireza

OK, let's give you this concept first before answering your question, in JavaScript Functions are Object, also null, Object, Arrays and even Date, so as you see there is nota simple way like typeof obj === 'object', so everything mentioned above will return true, but there are ways to check it with writing a function or using JavaScript frameworks, OK:

好的,让我们在回答你的问题之前先给你这个概念,在 JavaScript 中,函数是对象,也有空、对象、数组甚至日期,所以你看到没有像 typeof obj === 'object' 这样的简单方法,所以上面提到的所有内容都将返回 true,但是有一些方法可以通过编写函数或使用 JavaScript 框架来检查它,好吧:

Now, imagine you have this object that's a real object (not null or function or array):

现在,假设您有一个真实的对象(不是 null 或函数或数组):

var obj = {obj1: 'obj1', obj2: 'obj2'};

Pure JavaScript:

纯 JavaScript:

//that's how it gets checked in angular framework
function isObject(obj) {
  return obj !== null && typeof obj === 'object';
}

or

或者

//make sure the second object is capitalised 
function isObject(obj) {
   return Object.prototype.toString.call(obj) === '[object Object]';
}

or

或者

function isObject(obj) {
    return obj.constructor.toString().indexOf("Object") > -1;
}

or

或者

function isObject(obj) {
    return obj instanceof Object;
}

You can simply use one of these functions as above in your code by calling them and it will return true if it's an object:

您可以通过调用它们来简单地在代码中使用上述这些函数之一,如果它是一个对象,它将返回 true:

isObject(obj);

If you are using a JavaScript framework, they usually have prepared these kind of functions for you, these are few of them:

如果你使用的是 JavaScript 框架,他们通常为你准备了这些类型的函数,以下是其中的几个:

jQuery:

jQuery:

 //It returns 'object' if real Object;
 jQuery.type(obj);

Angular:

角度:

angular.isObject(obj);

Underscore and Lodash:

下划线和 Lodash:

//(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null)
_.isObject(obj);