简体   繁体   English

如何在 JavaScript 中将类变量初始化为空数组?

[英]How to initialize a class variable as an empty array in JavaScript?

I essentially just want to assign the default value of a class variable to an empty array.我本质上只是想将类变量的默认值分配给一个空数组。

I've tried the following, but did not have any luck:我试过以下,但没有任何运气:

class Test {
    constructor(myArray = []) {
        this.myArray = myArray;
    }
}

Obviously this doesn't work, as when I try to print Test.myArray, undefined is returned rather than an empty array.显然这不起作用,因为当我尝试打印 Test.myArray 时,返回的是 undefined 而不是空数组。

You are trying to access Prototype, your class is initialized correctly, just do:您正在尝试访问 Prototype,您的类已正确初始化,只需执行以下操作:

 class Test { constructor(myArray = []) { this.myArray = myArray; } } const t = new Test(); console.log(t.myArray)

new keyword means, that you are creating a new instance of the Test class. new关键字意味着您正在创建 Test 类的新实例

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

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