如何在JS类中添加数组声明

时间:2020-05-26 21:06:07

标签: javascript node.js

我需要这个简单代码的帮助,我需要在List类中声明数字数组,以便所有方法都可以从内部使用它。

let numbers  = [];

class List {
    add(number) {
        numbers.push(number);
    }
    get(number) {
        let index = numbers[number];
        return index;
    }
    remove(index) {
        numbers.splice(index, 1);
    }
    size() {
        return numbers.length;
    }
}

let list = new List();
list.add(5);
list.add(6);
list.add(7);
console.log(list.get(1));
list.remove(1);
console.log(list.get(1));

2 个答案:

答案 0 :(得分:0)

您可以在constructor中声明该数组,并使用this在其他方法中对其进行访问。这是更新的代码:

class List {
     constructor(){
          this.numbers = [];
     }
     add(number) {
          this.numbers.push(number);
     }
     get(number) {
          let index = this.numbers[number];
          return index;
     }
     remove(index) {
          this.numbers.splice(index, 1);
     }
     size() {
          return this.numbers.length;
     }
}
let list = new List();
list.add(5);
list.add(6);
list.add(7);
console.log(list.get(1));
list.remove(1);
console.log(list.get(1));

答案 1 :(得分:0)

我认为您期望这样的事情:

class List {
	constructor() {
		this.numbers = [];
	}
	
	add(number) {
		this.numbers.push(number);
	}
	
	getIndex(number) {
		return this.numbers.findIndex(item => item === number);
	}
	
	remove(number) {
		this.numbers = this.numbers.filter(item => item !== number);
	}
	
	removeByIndex(index) {
		this.numbers.splice(index, 1);
	}
	
	showNumbers() {
		return this.numbers;
	}
}

let list = new List();
list.add(5);
list.add(6);
list.add(7);
list.add(8);

console.log(list.showNumbers());
list.remove(7);
console.log(list.showNumbers());
list.removeByIndex(list.getIndex(8));
console.log(list.showNumbers());
.as-console-wrapper {min-height: 100%!important; top: 0}