我有以下代码练习:
创建包含下一个字段的类实习生:名称(字符串)姓氏(字符串)惰性(数字从20到50)好奇(数字从0到100)技能(数字从0到100)不负责任(浮点数从0.0到1.0)这个类创建了计算实习生“标记”的方法,该方法由公式计算
问:如何向类中的原始数据类型添加约束?就像int,但范围在20到50之间。或者是绳子。下面是我没有约束的代码:
class Intern {
constructor(name, surname, laziness, curiosity, skill, irresponsibility) {
this.name = name
this.surname = surname
this.laziness = laziness
this.curiosity = curiosity
this.skill = skill
this.irresponsibility = irresponsibility
}
getMark() {
let mark = (((this.skill+this.curiosity)*(1.5 - this.irresponsability))/(this.laziness*0.25));
return mark
}}
发布于 2022-04-05 18:55:57
如果给定的值超出了约束范围,您希望发生什么?实习生应该得到一个默认值吗?
我会对每个属性进行if语句,并检查给定值是否大于最低约束,是否小于最高值:
class Intern {
constructor(name, surname, laziness, curiosity, skill, irresponsibility) {
this.name = name
this.surname = surname
if(laziness<=50 && laziness>=20){
this.laziness = laziness
}
if(curiosity<=100 && curiosity>=0){
this.curiosity = curiosity
this.skill = skill
this.irresponsibility = irresponsibility
}
getMark() {
let mark = (((this.skill+this.curiosity)*(1.5 - this.irresponsability))/(this.laziness*0.25));
return mark
}<=和>=运算符检查该值是否小于或等于或大于或等于。
https://stackoverflow.com/questions/71756924
复制相似问题