gpt4 book ai didi

arrays - 用类实例填充数组

转载 作者:太空宇宙 更新时间:2023-11-03 22:06:48 24 4
gpt4 key购买 nike

我在填充类实例数组时遇到了困难。为了长话短说,我创建了一个 person 类(其上有属性和函数),并且我想填充一个 person 实例数组,只需插入该 person 类的数组"new"实例即可。结果,数组中充满了许多指向最后创建的实例的元素。

这里是一个简化的示例代码。 https://repl.it/@expovin/ArrayOfClassInstances

let p={
name:"",
age:""
}

class Person {

constructor(name, age){
p.name=name;
p.age=age;
}

greeting(){
console.log("Hi, I'm ",p);
}

gatOler(){
p.age++;
}
}

module.exports = Person;

它的用法如下:

let person = require("./Person");

var crowd = [];


console.log("Let's create an instance of Person in the crowd array");
crowd.push(new person("Vinc", 40));
console.log("Instance a is greeting");
crowd[0].greeting();

console.log("Let's add a new instance of Person as next element in the same array");
crowd.push(new person("Jack", 50));
crowd[1].greeting();

console.log("I expect to have two different people in the array");
crowd.forEach( p => p.greeting());

我的错在哪里?

预先感谢您的帮助

最佳答案

您有一个不属于类的变量,每次您创建新的 person 实例时,它都会被重置。相反,让它成为类 person 的属性,所以它看起来像这样:

class Person {

constructor(name, age){
this.p = {
name, age
}
}

greeting(){
console.log("Hi, I'm ", this.p);
}
}

您还可以将它们拆分为自己的变量:

class Person {

constructor(name, age){
this.name = name;
this.age = age;
}

greeting(){
console.log("Hi, I'm ", this.name, this.age);
}
}

关于arrays - 用类实例填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52917012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com