Javascript 检查JS对象类型的最准确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7893776/
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 03:58:29  来源:igfitidea点击:

The most accurate way to check JS object's type?

javascript

提问by Royi Namir

The typeofoperator doesn't really help us to find the real type of an object.

typeof运营商并没有真正帮助我们找到真正的类的一个对象。

I've already seen the following code :

我已经看到以下代码:

Object.prototype.toString.apply(t)  

Question:

题:

Is it the mostaccurate way of checking the object's type?

这是检查对象类型的准确方法吗?

回答by kmatheny

The JavaScript specification gives exactly one proper way to determine the class of an object:

JavaScript 规范提供了一种正确的方法来确定对象的类:

Object.prototype.toString.call(t);

http://bonsaiden.github.com/JavaScript-Garden/#types

http://bonsaiden.github.com/JavaScript-Garden/#types

回答by wiky

the Object.prototype.toStringis a good way, but its performance is the worst.

Object.prototype.toString是一个好方法,但它的性能是最差的。

http://jsperf.com/check-js-type

http://jsperf.com/check-js-type

check js type performance

检查js类型性能

Use typeofto solve some basic problem(String, Number, Boolean...) and use Object.prototype.toStringto solve something complex(like Array, Date, RegExp).

使用typeof解决一些基本问题(字符串,数字,布尔...)和使用Object.prototype.toString来解决复杂的东西(如数组,日期,正则表达式)。

and this is my solution:

这是我的解决方案:

var type = (function(global) {
    var cache = {};
    return function(obj) {
        var key;
        return obj === null ? 'null' // null
            : obj === global ? 'global' // window in browser or global in nodejs
            : (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function
            : obj.nodeType ? 'object' // DOM element
            : cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math
            || (cache[key] = key.slice(8, -1).toLowerCase()); // get XXXX from [object XXXX], and cache it
    };
}(this));

use as:

用于:

type(function(){}); // -> "function"
type([1, 2, 3]); // -> "array"
type(new Date()); // -> "date"
type({}); // -> "object"

回答by parliament

Accepted answer is correct, but I like to define this little utility in most projects I build.

接受的答案是正确的,但我喜欢在我构建的大多数项目中定义这个小实用程序。

var types = {
   'get': function(prop) {
      return Object.prototype.toString.call(prop);
   },
   'null': '[object Null]',
   'object': '[object Object]',
   'array': '[object Array]',
   'string': '[object String]',
   'boolean': '[object Boolean]',
   'number': '[object Number]',
   'date': '[object Date]',
}

Used like this:

像这样使用:

if(types.get(prop) == types.number) {

}

If you're using angular you can even have it cleanly injected:

如果您使用的是 angular,您甚至可以干净地注入它:

angular.constant('types', types);

回答by Raynos

var o = ...
var proto =  Object.getPrototypeOf(o);
proto === SomeThing;

Keep a handle on the prototype you expect the object to have, then compare against it.

保持对您期望对象具有的原型的句柄,然后与它进行比较。

for example

例如

var o = "someString";
var proto =  Object.getPrototypeOf(o);
proto === String.prototype; // true

回答by David

I'd argue that most of the solutions shown here suffer from being over-engineerd. Probably the most simple way to check if a value is of type [object Object]is to check against the .constructorproperty of it:

我认为这里显示的大多数解决方案都受到过度设计的影响。检查值是否属于类型的最简单方法可能[object Object]是检查.constructor它的属性:

function isObject (a) { return a != null && a.constructor === Object; }

or even shorter with arrow-functions:

甚至更短的箭头函数:

const isObject = a => a != null && a.constructor === Object;

The a != nullpart is necessary because one might pass in nullor undefinedand you cannot extract a constructor property from either of these.

a != null部分是必要的,因为可能会传入null或者undefined您无法从其中任何一个中提取构造函数属性。

It works with any object created via:

它适用于通过以下方式创建的任何对象:

  • the Objectconstructor
  • literals {}
  • Object构造
  • 文字 {}

Another neat feature of it, is it's ability to give correct reports for custom classes which make use of Symbol.toStringTag. For example:

它的另一个巧妙功能是能够为使用Symbol.toStringTag. 例如:

class MimicObject {
  get [Symbol.toStringTag]() {
    return 'Object';
  }
}

The problem here is that when calling Object.prototype.toStringon an instance of it, the false report [object Object]will be returned:

这里的问题是当调用Object.prototype.toString它的一个实例时,[object Object]会返回错误的报告:

let fakeObj = new MimicObject();
Object.prototype.toString.call(fakeObj); // -> [object Object]

But checking against the constructor gives a correct result:

但是检查构造函数会给出正确的结果:

let fakeObj = new MimicObject();
fakeObj.constructor === Object; // -> false

回答by beliha

The best way to find out the REAL type of an object (including BOTH the native Object or DataType name (such as String, Date, Number, ..etc) AND the REAL type of an object (even custom ones); is by grabbing the name property of the object prototype's constructor:

找出对象的真实类型(包括本机对象或数据类型名称(例如字符串、日期、数字等)和对象的真实类型(甚至自定义类型)的最佳方法;是通过抓取对象原型的构造函数的 name 属性:

Native Type Ex1:

本机类型 Ex1:

var string1 = "Test";
console.log(string1.__proto__.constructor.name);

displays:

显示:

String

Ex2:

例2:

var array1 = [];
console.log(array1.__proto__.constructor.name);

displays:

显示:

Array

Custom Classes:

自定义类:

function CustomClass(){
  console.log("Custom Class Object Created!");
}
var custom1 = new CustomClass();

console.log(custom1.__proto__.constructor.name);

displays:

显示:

CustomClass

回答by Codebeat

Old question I know. You don't need to convert it. See this function:

我知道的老问题。你不需要转换它。看到这个函数:

function getType( oObj )
{
    if( !!oObj && typeof oObj === "object" )
    {
       // Check if it is an alien object, for example created as {world:'hello'}
       if( typeof oObj.constructor !== "function" )
        { return 'Object'; }

      return oObj.constructor.name; 
    }   

    return false;
}; 

Examples:

例子:

function MyObject() {}; // Just for example

console.log( getType( new String( "hello ") )); // String
console.log( getType( function() {} ));         // Function
console.log( getType( {} ));                    // Object
console.log( getType( new MyObject() ));        // MyObject

Low cost and simple.

成本低,操作简单。

回答by Abraham Juliot

I put together a little type check utility inspired by the above correct answers:

受上述正确答案的启发,我整理了一个小类型检查实用程序:

thetypeof = function(name) {
        let obj = {};
        obj.object = 'object Object'
        obj.array = 'object Array'
        obj.string = 'object String'
        obj.boolean = 'object Boolean'
        obj.number = 'object Number'
        obj.type = Object.prototype.toString.call(name).slice(1, -1)
        obj.name = Object.prototype.toString.call(name).slice(8, -1)
        obj.is = (ofType) => {
            ofType = ofType.toLowerCase();
            return (obj.type === obj[ofType])? true: false
        }
        obj.isnt = (ofType) => {
            ofType = ofType.toLowerCase();
            return (obj.type !== obj[ofType])? true: false
        }
        obj.error = (ofType) => {
            throw new TypeError(`The type of ${name} is ${obj.name}: `
            +`it should be of type ${ofType}`)
        }
        return obj;
    };

example:

例子:

if (thetypeof(prop).isnt('String')) thetypeof(prop).error('String')
if (thetypeof(prop).is('Number')) // do something