Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript类构造函数初始化数组_Javascript_Arrays_Object_Constructor - Fatal编程技术网

javascript类构造函数初始化数组

javascript类构造函数初始化数组,javascript,arrays,object,constructor,Javascript,Arrays,Object,Constructor,所以我想知道如何在类构造函数中初始化数组: class test{ constructor(){ //here i want to initialize a new array called "array" from the class "class2" let array = [new class2()]; //is this the way to do it? } add(x){ for(let i=0; i<

所以我想知道如何在类构造函数中初始化数组:

class test{

    constructor(){
        //here i want to initialize a new array called "array" from the class "class2"
        let array = [new class2()]; //is this the way to do it?
    }

    add(x){
        for(let i=0; i<array.length; i++){
            if(array[i] == null){
                array[i] = x;
                break;
            }
        }
    }
}
类测试{
构造函数(){
//这里我想从类“class2”中初始化一个名为“array”的新数组
让array=[new class2()];//这样做吗?
}
加(x){

对于(设i=0;i,初始化的变量将绑定到构造函数上下文。这意味着您可以在构造函数中再次使用它们,但在该函数之外无法访问

由于您使用的是ES6类,因此可以添加一个包含此数组的类变量。您需要使用
this
访问它,但它可以正常工作

class test{


    constructor(){
        // this variable will be accessible from everywhere in the class
        this.array = [new class2()]; 
    }

    add(x){
        for(let i = 0; i < this.array.length; i++){
            if(this.array[i] == null){
                this.array[i] = x;
                break;
            }
        }
    }
}
类测试{
构造函数(){
//可以从类中的任何位置访问此变量
this.array=[new class2()];
}
加(x){
for(设i=0;i
您可以使用class2扩展类,并使用
super()
函数从class2委托值