每次调用特定方法时,将方法参数值增加1



我遇到问题的两项任务:

任务1:将猫的初始年龄设置为5到10 之间的随机数

  • 如何防止随机年龄被覆盖

任务2:修改类,使猫的年龄每说话五次就增加1岁。

class Cat {
name;
age;
constructor(name) {
!name ? this.setName("Norman") : this.setName(name);
this.age = null;
}
getName() {
return this.name
}
getAge() {
return this.age
}
setName(name) {
this.name = name;
}
setAge(age) {
age = Math.floor(Math.random() * 6) + 5;
this.age = age
}
speak(sound) {
this.sound = sound
}
}

(1(如果您希望初始年龄是随机的,请将随机计算放入构造函数中。让年龄设定者像其他人一样,不要理会参数。。。

constructor(name) {
!name ? this.setName("Norman") : this.setName(name);
this.age = Math.floor(Math.random() * 5) + 5;  // note - 5 to 10
}
setAge(age) {
this.age = age;
}

(2(speak方法可以用更多的实例数据来跟踪其调用。在构造函数中初始化它,在speak()上递增它,并在那里测试它(因为它是5的倍数(。

constructor(name) {
!name ? this.setName("Norman") : this.setName(name);
this.age = Math.floor(Math.random() * 5) + 5;
this.spoken = 0;
}
speak(sound) {
this.sound = sound;
this.spoken++;
if (this.spoken % 5 === 0) {
this.age++;
}
}

最新更新