Node.js
Quiz oynatma
run metoduyla soruları sırayla sormayı öğrenirsin.
run metodu ile soru oynatma
Şimdi Quiz sınıfına bir run metodu ekleyeceğiz. Bu metod soruları sırayla yazdırır. Örnek: run() { for (let i = 0; i < this.questions.length; i++) { console.log(this.questions[i].text); } }.
for döngüsü ile sorular dizisini baştan sona gezeriz. this.questions[i] her soruyu verir; .id ve .text ile özelliklerine erişiriz. Çıktı şöyle olur: Soru 1: Başkent?, Soru 2: En büyük şehir?. Bu, quiz'in temel işlevidir: soruları kullanıcıya göstermek. Gerçek bir uygulamada her sorudan sonra kullanıcıdan yanıt alınırdı; burada yalnızca yazdırıyoruz. Önceki dersin çözümünü alıp run metodunu ekleyeceğiz.
for döngüsü ile gezme
for (let i = 0; i < this.questions.length; i++) bir diziyi baştan sona gezer. i sıfırdan başlar, length'e kadar artar. this.questions[i] ile her öğeye erişirsin.
Bu, JavaScript'te bir diziyi dolaşmanın temel yoludur. i < length koşulu dizinin sonunda durur. i++ her adımda bir artırır. Döngü gövdesinde this.questions[i].id ve this.questions[i].text ile her sorunun özelliklerine erişilir. Çıktı: Soru 1: Başkent?, Soru 2: En büyük şehir?. Bu desen, soruları bir tabloda göstermek, bir listede sıralamak veya sırayla işlemek için kullanılır.
Uygulama run metodunu ekle
Önceki dersin çözümünü al. Quiz sınıfına run() metodu ekle: for (let i = 0; i < this.questions.length; i++) { console.log("Soru " + this.questions[i].id + ": " + this.questions[i].text); }. Son satır hazır: quiz.run();
Örnek çözümü göster
class Question {
constructor(id, text, answer) {
this.id = id;
this.text = text;
this.answer = answer;
}
}
class Quiz {
constructor() {
this.questions = [];
}
addQuestion(text, answer) {
const id = this.questions.length + 1;
this.questions.push(new Question(id, text, answer));
}
run() {
for (let i = 0; i < this.questions.length; i++) {
console.log("Soru " + this.questions[i].id + ": " + this.questions[i].text);
}
}
}
const quiz = new Quiz();
quiz.addQuestion("Başkent?", "Ankara");
quiz.addQuestion("En büyük şehir?", "İstanbul");
quiz.run();
Kendini test et
-
Parçayı rolüne eşle
- run()
- Soruları yazdırır
- for döngüsü
- Soruları sırayla gezer
- this.questions[i]
- Tek bir soruyu verir
- .text
- Soru metni
-
for döngüsü koşulunu tamamla
for (let i = 0; i < this.questions.____; i++) { console.log(i); }
Cevabı göster
for (let i = 0; i < this.questions.length; i++) { console.log(i); }
-
this.questions[i] ne verir?
this.questions[i]
- Dizinin uzunluğunu
- Tüm soruları
- Soru sayısını
- Tek bir soruyu
Cevabı göster
Tek bir soruyu — questions[i] dizinin i. öğesini (tek soru) verir.
Sıradaki ders: Skor hesaplama