简体   繁体   English

为什么javascript的typeof总是返回“object”?

[英]Why javascript's typeof always return "object"?

What's it used for if it always returns object as type?如果它总是返回object作为类型,它有什么用?

always for Elements or lists .总是用于Elementslists

JS's typeof doesn't always return 'object', but it does return object for things which people may not consider to be objects -- ie arrays, and also, oddly, for nulls. JS的typeof并不总是返回'object',但它确实返回了人们可能不认为是对象的对象 - 即数组,而且奇怪的是,返回null。

For arrays this is correct, because as far as JS is concerned, arrays are objects; 对于数组,这是正确的,因为就JS而言,数组是对象; they're the same thing. 他们是一回事。 Array is just another class, and you can instantiate objects of type Array, but they're still treated as objects. Array只是另一个类,您可以实例化Array类型的对象,但它们仍然被视为对象。

This page has a list of types in JS, along with the response you'll get for each of them from typeof. 此页面包含JS中的类型列表,以及您从typeof获得的每个类型的响应。 It also has some JS code to override the typeof function with one that returns more useful information. 它还有一些JS代码来覆盖typeof函数,返回更多有用的信息。 If you're worried about it not being useful, you could implement something like that if you wish. 如果你担心它没用,你可以实现类似的东西。

It doesn't always return "object": 它并不总是返回“对象”:

alert(typeof "hello");

That said, a (possibly) more useful trick to examine objects is to use Object.prototype.toString.call() and look at the result: 也就是说,检查对象的一个​​(可能)更有用的技巧是使用Object.prototype.toString.call()并查看结果:

var t = Object.prototype.toString.call(itIsAMystery);

That will give you a string like [object Foo] with "Foo" being the constructor (I think) the interesting part. 这会给你一个像[object Foo]这样的字符串,其中“Foo”是 构造函数(我认为) 有趣的部分。 For "native" types (like Date or String) you get back that constructor name. 对于“本机”类型(如Date或String),您将获得该构造函数名称。

In my experience, the main problem with typeof comes from distinguishing between arrays, objects, and nulls (all return "object"). 根据我的经验,typeof的主要问题来自于区分数组,对象和空值(都返回“对象”)。

To do this, I first check typeof then I check the null case or the "object's" constructor, like this: 为此,我首先检查typeof然后检查null case或“object”的构造函数,如下所示:

for (o in obj) {
    if (obj.hasOwnProperty(o)) {
        switch (typeof obj[o]) {
            case "object":
                if (obj[o] === null) {
                    //do somethign with null
                } else {
                    if (obj[o].constructor.name === "Array") {
                        //do something with an Array
                    } else {
                        //do something with an Object
                    }
                }
                break;
            case "function":
                //do something with a function
                break;
            default:
                //do something with strings, booleans, numbers
                break;
        }
    }
}

One needs to be a little careful with the typeof operator. 人们需要对typeof运算符小心谨慎。 It returns "object" for a null, "number" for NaN, "number" for Infinity, "object" for a "new Number(1)" and "object" for an array. 它返回null的“object”,NaN的“number”,Infinity的“number”,“new Number(1)”的“object”和数组的“object”。

When checking for the existence of a variable (typeof variable !== "undefined") one sometimes needs to first check if (variable == null) because typeof returns "object" for a variable that is assigned to null. 当检查是否存在变量(typeof variable!==“undefined”)时,有时需要先检查if(variable == null),因为typeof为赋值为null的变量返回“object”。

This is a bit obvious but one also has to be careful not to invoke a function when checking typeof because the return type of the function will be reported and not "function". 这有点明显,但是在检查typeof时也必须小心不要调用函数,因为函数的返回类型将被报告而不是“function”。

To add in with the others, typeof returns both objects and primitives. 要添加其他内容,typeof将返回对象和基元。 There are 5 primitive types in javascript: undefined, null, boolean, string and number. javascript中有5种原始类型:undefined,null,boolean,string和number。 All else is an object. 所有其他都是一个对象。 When typeof is applied to any object type other than Function, it simply returns “object”. 当typeof应用于除Function之外的任何对象类型时,它只返回“object”。 When applied to a function, it returns a function object. 应用于函数时,它返回一个函数对象。

So, for example: 所以,例如:

  • typeof true; typeof true; //returns the primitive type "boolean" //返回基本类型“boolean”
  • typeof 123; 123型; //returns the primitive type "number" //返回基本类型“数字”
  • typeof null //returns "object" which is a mistake, but so far there is no fix in another ECMAScript version, just talk about doing so. typeof null //返回“对象”这是一个错误,但到目前为止还没有另一个ECMAScript版本的修复,只是谈论这样做。
  • typeof object //returns "object", which makes sense typeof对象//返回“对象”,这是有道理的

To expound further on Pointy's answer, there is in every JavaScript object an internal property known as [[Class]] in ECMAScript 5. In order to display the actual value of the object, you can reference the [[Class]] property using: Object.prototype.toString . 为了进一步阐述Pointy的答案,每个JavaScript对象中都有一个ECMAScript 5中称为[[Class]]的内部属性。为了显示对象的实际值,可以使用以下参考[[Class]]属性: Object.prototype.toString To avoid some of the specialized built-in objects overwriting toString you use the internal method of Call that will reveal the actual object type. 为了避免某些专门的内置对象覆盖toString,您可以使用Call的内部方法来显示实际的对象类型。

So instead of getting the generic object back from toString: 因此,而不是从toString返回通用对象:

var dateObject = Object.prototype.toString(new Date);
document.write(dateObject);//[object Object]

You can get the actual object type using Call: 您可以使用Call获取实际的对象类型:

var dateObject = Object.prototype.toString.call(new Date);
document.write(dateObject);//[object Date]

typeof is an operator that accepts one operand, that returns a string indicating whether the operand is a primitive, a function, an object, or undeclared . typeof是一个接受一个操作数的运算符,它返回一个字符串,指示该操作数是原语、function、object 还是 undeclared

Note that typeof does not return strings that correspond to the name of the class or constructor function used to construct an object, hence your question.请注意, typeof不返回与 class 或用于构造 object 的构造函数 function 的名称相对应的字符串,因此您的问题。

typeof returns the following for the seven primitive JavaScript types: typeof七种原始 JavaScript 类型返回以下内容:

  1. Undefined: 'undefined'未定义: 'undefined'
  2. Null: 'object' Null: 'object'
  3. Boolean: 'boolean' Boolean: 'boolean'
  4. Number: 'number'号码: 'number'
  5. BigInt: 'bigint'大整数: 'bigint'
  6. Symbol: 'symbol'符号: 'symbol'
  7. String: 'string'字符串: 'string'

(...and for the proposed BigDecimal primitive type , I presume it will return 'bigdecimal' .) (...对于提议的 BigDecimal 原始类型,我认为它将返回'bigdecimal' 。)

typeof returns the following for objects/object categories: typeof为对象/对象类别返回以下内容:

  1. document.all : 'undefined' document.all'undefined'
  2. functions: 'function'功能: 'function'
  3. all other ordinary objects: 'object'所有其他普通对象: 'object'

...and, finally, typeof returns 'undefined' for undeclared identifiers. ...最后, typeof为未声明的标识符返回'undefined'

Notes笔记

typeof returns 'object' for null , even though null is of type Null , due to an early requirement for easy interoperability with Java , a language in which null is the empty reference type . typeof returns 'object' for null , even though null is of type Null , due to an early requirement for easy interoperability with Java , a language in which null is the empty reference type . null sits at the top of every prototype chain, and can be thought of as being within the set of object-type primitives. null位于每个原型链的顶部,可以被认为是在对象类型原语集中。

typeof returns 'function' for functions, and not 'object' , to enable easy identification of functions (ie. callable objects) without having to expose within the language a separate isFunction or isCallable function. typeof为函数返回'function'而不是'object'以便轻松识别函数(即可调用对象),而无需在语言中公开单独的isFunctionisCallable function。

typeof provides the ONLY mechanism in JavaScript to detect undeclared identifiers (see step 2a in the spec here ) without throwing an error. typeof在 JavaScript 中提供了唯一的机制来检测未声明的标识符(请参阅此处规范中的步骤 2a )而不会引发错误。 This is useful when attempting to dynamically detect the host environment (eg. Node.js or a Web browser), where a tested-for identifier may or may not exist.这在尝试动态检测主机环境(例如 Node.js 或 Web 浏览器)时很有用,其中经过测试的标识符可能存在也可能不存在。

Attempting to use typeof with an identifier within a temporal dead zone throws a runtime error (ie. normal behavior).尝试在临时死区内使用带有标识符的typeof会引发运行时错误(即正常行为)。

document.all is an object in the Web platform (ie. not part of the language) for which typeof returns undefined . document.all是 Web 平台中的 object (即不是语言的一部分), typeof返回undefined This anomaly is accommodated in the language specification in order to maintain compatibility with early Web browsers.为了保持与早期 Web 浏览器的兼容性,此异常已包含在语言规范中。

Primitive wrapper objects like new Number(1) and new Boolean(true) are treated as objects, not primitives.new Number(1)new Boolean(true)这样的原始包装对象被视为对象,而不是原始对象。 So, for example, typeof new Number(1) returns 'object' .因此,例如, typeof new Number(1)返回'object' Note that typeof Number(1) returns 'number' because without the new operator, these kind of constructor functions return an instance of the primitive.请注意typeof Number(1)返回'number'因为没有new运算符,这些类型的构造函数返回原语的实例。

typeof is an operator, not a function. typeof是一个运算符,而不是 function。 Although it can be used with a syntax that looks like a bit like a function call (eg typeof(foo) ), the right-had side of the expression is a normal unary expression: the parentheses do not delineate a function call, but an expression.虽然它可以与看起来有点像 function 调用(例如typeof(foo) )的语法一起使用,但表达式的右边是一个普通的一元表达式:括号不描绘 function 调用,而是表达。

Not all typeof returns objects. 并非所有typeof都返回对象。

Objects, Arrays and RegEx returns a type of object . 对象,数组RegEx返回一种object

Function which is an object (reference type), yet returns type of function . 函数 ,它是一个对象(引用类型),但返回的类型function That's an inconsistency in the language. 这是语言的不一致。

Another thing to note, undefined returns undefined while null returns object which is a bug in JS. 另外需要注意的是, undefined返回undefinednull返回object ,这是JS中的一个bug。

NaN (not a number) returns a type of number . NaN (不是数字)返回一种number

Better you keep track of all these and be aware of these strange behaviors. 更好地跟踪所有这些,并了解这些奇怪的行为。

For your reference here are all the type of values: 这里有所有类型的值供您参考:

typeof "Tamal" ---> string
typeof 100 ---> number
typeof true ---> boolean
typeof false ---> boolean
typeof undefined ---> undefined
typeof function() {} ---> function
typeof Symbol() ---> symbol
typeof {name: "Tamal"} ---> object
typeof [1, 2, 3] ---> object
typeof /^/ ---> object
typeof NaN ---> number
typeof null ---> object (bug)

You have to understand that the type system in JavaScript is dynamic with a few "primative" types to build upon. 您必须了解JavaScript中的类型系统是动态的,并且需要构建一些“主要”类型。 By treating all complex objects as the type "object" this allows you to duck-type and call methods without necessarily having to know the type of the object being passed around assuming that type has the function call implemented. 通过将所有复杂对象视为“对象”类型,这允许您进行duck-type和调用方法,而不必知道传递的对象的类型,假设该类型具有实现的函数调用。 In a dynamic programming language everything is an "object". 在动态编程语言中,一切都是“对象”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM