简体   繁体   English

为什么 typeof Array 返回“函数”而 typeof [数组变量] 返回“对象”?

[英]Why does typeof Array returns “function” and typeof [array variable] returns an “Object”?

I had a chance to met this question but unable to find an answer.我有机会遇到这个问题,但无法找到答案。

var arr = [];

Why does typeof Array returns "function" and typeof arr returns an "Object" ?为什么typeof Array返回"function"typeof arr返回"Object"

Can anyone explain please.谁能解释一下。

When you write typeof Array , it means that you are getting type of constructor function.当您编写typeof Array时,这意味着您正在获取构造函数 function 的类型。 As class is under the hood is constructor function.由于class在引擎盖下是构造函数 function。 Let me show an example:让我举个例子:

class Person {
    constructor(firstName, lastName, address) {
        this.firstName= firstName;
        this.lastName = lastName;
        this.address= address;
    }

    getFullName () {
        return this.firstName + " " + this.lastName ;
    }
}

and to create an instance of the class:并创建 class 的实例:

let car = new Person ("Jon", "Freeman", "New York");

In the above code, we've created a variable car which references to function construtor defined in the class:在上面的代码中,我们创建了一个变量car ,它引用了 class 中定义的 function 构造函数:

function Person (firstName, lastName, address) {
        this.firstName = firstName,
        this.lastName = lastName,
        this.address = address,
        this.getFullName = function () {
            return this.firstName+ " " + this.lastName;
        }
}

So this is a reason why typeof Array returns function .所以这就是typeof Array返回function的原因。

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

相关问题 typeof(Array,null)返回object,typeof(null,Array)返回function - typeof (Array, null) returns object and typeof(null, Array) returns function 为什么“typeof + ''”返回'number'? - Why “typeof + ''” returns 'number'? 为什么javascript typeof总是返回“对象” - Why javascript typeof returns always “object” 为什么`typeof false || undefined`返回“布尔值” - Why does `typeof false || undefined` returns “boolean” typeof 对象但不是数组 - typeof object but not array typeof为`this`返回“object”,在其他地方返回“number” - typeof returns “object” for `this`, “number” elsewhere 为什么我的条件不认为typeof返回为“ undefined”的数组的未定义值? - Why is an undefined value of an array of array that typeof returns as “undefined” not considered true by my conditional? typeof typeof x 返回字符串而不是对象,因为 null 的类型是对象 - typeof typeof x returns string and not object since type of null is object Array对象与Object是否不相同(两者的typeof都返回相同的值)? - Isn't the Array object different from the Object (thought typeof on both returns the same value)? 当 typeof 在 function 上运行时,它返回“function”作为类型。 为什么它不返回“对象”? - When typeof is run on a function, it returns “function” as the type. Why doesn't it return “object”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM