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

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

Why javascript's typeof always return "object"?

javascripttypeof

提问by Tom Brito

What's it used for if it always returns objectas type?

如果它总是object作为类型返回,它有什么用?

always for Elementsor lists.

始终用于元素列表

回答by Spudley

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 并不总是返回“对象”,但它确实为人们可能不认为是对象的东西返回对象——即数组,而且奇怪的是,对于空值。

For arrays this is correct, because as far as JS is concerned, arrays are objects; 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.

对于数组,这是正确的,因为就 JS 而言,数组是对象;它们是一样的。Array 只是另一个类,您可以实例化 Array 类型的对象,但它们仍被视为对象。

This pagehas a list of types in JS, along with the response you'll get for each of them from typeof. It also has some JS code to override the typeof function with one that returns more useful information. If you're worried about it not being useful, you could implement something like that if you wish.

此页面包含 JS 中的类型列表,以及您将从 typeof 中获得的每种类型的响应。它还具有一些 JS 代码,可以使用返回更多有用信息的函数来覆盖 typeof 函数。如果您担心它没有用,您可以根据需要实现类似的功能。

回答by Pointy

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. For "native" types (like Date or String) you get back that constructor name.

这会给你一个字符串,比如[object Foo]“Foo”是构造函数(我认为)有趣的部分。对于“本机”类型(如日期或字符串),您会返回该构造函数名称。

回答by Tamal Anwar Chowdhury

Not all typeof returns objects.

并非所有 typeof 都返回对象。

Objects, Arraysand RegExreturns a type of object.

对象、数组和正则表达式返回object.

Functionwhich is an object (reference type), yet returns type of function. That's an inconsistency in the language.

函数是一个对象(引用类型),但返回function. 这是语言上的不一致。

Another thing to note, undefinedreturns undefinedwhile nullreturns objectwhich is a bug in JS.

另一件事要注意,undefined返回undefinednull返回object,这是 JS 中的一个错误。

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)

回答by AutoSponge

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 或“对象的”构造函数,如下所示:

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;
        }
    }
}

回答by Grant Nyland

One needs to be a little careful with the typeof operator. It returns "object" for a null, "number" for NaN, "number" for Infinity, "object" for a "new Number(1)" and "object" for an array.

需要对 typeof 运算符稍加小心。它为 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")是否存在时,有时需要首先检查是否(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 时还必须注意不要调用函数,因为将报告函数的返回类型而不是“函数”。

回答by James Drinkard

To add in with the others, typeof returns both objects and primitives. There are 5 primitive types in javascript: undefined, null, boolean, string and number. All else is an object. When typeof is applied to any object type other than Function, it simply returns “object”. When applied to a function, it returns a function object.

为了与其他人相加, typeof 返回对象和原语。JavaScript 中有 5 种原始类型:undefined、null、boolean、string 和 number。其他都是一个对象。当 typeof 应用于除 Function 之外的任何对象类型时,它只返回“object”。当应用于函数时,它返回一个函数对象。

So, for example:

因此,例如:

  • typeof true; //returns the primitive type "boolean"
  • typeof 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 object //returns "object", which makes sense
  • 类型为真;//返回原始类型“boolean”
  • 类型为 123;//返回原始类型“数字”
  • typeof null //returns "object" 这是一个错误,但目前在另一个 ECMAScript 版本中还没有修复,只是谈谈这样做。
  • typeof object //返回“object”,这是有道理的

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. 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.

为了进一步阐述 Pointy 的答案,在 ECMAScript 5 中,每个 JavaScript 对象都有一个称为 [[Class]] 的内部属性。为了显示对象的实际值,您可以使用以下方法引用 [[Class]] 属性:Object.prototype.toString. 为了避免一些专门的内置对象覆盖 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]

回答by Achilles

You have to understand that the type system in JavaScript is dynamic with a few "primative" types to build upon. 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. In a dynamic programming language everything is an "object".

你必须明白 JavaScript 中的类型系统是动态的,有一些“原始”类型可以构建。通过将所有复杂对象视为类型“对象”,这允许您进行类型化和调用方法,而不必知道传递的对象的类型,假设该类型实现了函数调用。在动态编程语言中,一切都是“对象”。