ค้นหาเว็บไซต์

typescript - หยุด(ส่งกลับ)โค้ดจากเมธอดลูกใน Angular 6


ฉันมีโปรเจกต์ Angular 6 และฉันต้องการหยุดโค้ดจากเมธอดของลูก ตัวอย่างเช่น ในตัวอย่างด้านล่าง ถ้า studentNo มากกว่า 15 ฉันไม่ต้องการให้ alert("studentAge") ทำงาน หรือพูดอีกอย่างคือ ฉันต้องการหยุดโค้ดจากเมธอด calculate ฉันจะทำอย่างไรได้บ้าง?

doSomething(studentAge){
 this.calculate(studentAge);

 alert(studentAge);
}

calculate(studentAge){
  if(studentAge > 15){ return; }
  else{ studentAge += 20 }
}

คำตอบ #1

TypeScript ส่งค่าตัวแปรโดย ค่า

การแก้ไข studentAge ภายใน calculate() จะไม่เปลี่ยนค่าของมันใน doSomething() เพราะสิ่งที่ calculate() รับมาคือ ค่าของ studentAge ดังนั้นวิธีนี้จึงไม่ทำอะไรเลย

นี่คือสิ่งที่ฉันเดาว่าคุณอยากทำจริง ๆ:

doSomething(studentAge: number) {
  studentAge = this.calculate(studentAge);
  if (studentAge <= 15) {
    alert(studentAge);
  }
}

calculate(studentAge: number): number {
  if (studentAge > 15) { 
    return studentAge; 
  }
  else { 
    return studentAge + 20;
  }
}