简体   繁体   中英

Javascript For Loop and Function won't return anything

When i execute this page no promts are showing up. What am I missing to get this to work? I'm relatively new to JavaScript so any kind of help would be appreciated!

function calc(correct, answer) {
  if (correct == answer) {
    alert("You hit the jackpot!");
  } else {
    alert("WRONG! the correct answer is: " + answer);
  }
}

var questions = ["2 x 10", "5 + 15", "25 - 20", "100 / 10", "9 x 2", "20 + 3", "5 - 5", "5 / 10", "1 + 11111", "0 + 14"];
var answers = [ 2 * 10,   5 + 15,   25 - 20,   100 / 10,   9 * 2,   20 + 3,   5 - 5,   5 / 10,   1 + 11111,   0 + 14 ];

for (var i=0; i<10; i++) {
  var answer = promt(questions[i]);
  calc(answer, answers[i]);
}

这是您的错字:提示而不是提示

You should use 'prompt'. And before calling to Calc method you should also check for null.

Try this:

var questions = ["2 x 10", "5 + 15", "25 - 20", "100 / 10", "9 x 2", "20 + 3", "5 - 5", "5 / 10", "1 + 11111", "0 + 14"];
var answers = [ 2 * 10,   5 + 15,   25 - 20,   100 / 10,   9 * 2,   20 + 3,   5 - 5,   5 / 10,   1 + 11111,   0 + 14 ];

for (var i=0; i<10; i++) {
    (answers[i] == prompt(questions[i])) ?
    alert("You hit the jackpot!") :
    alert("WRONG! the correct answer is: " + answers[i])
}

Beside that you have the typo prompt other noticed, you might have issues in your game-flow cause your for loop might prompt you only once and exit.

Here's something more fun and interesting: demo

var i = 0,
    playerScore = 0,
    QA = [
           ["2 x 10" , 2*10,  2],  //["Q", A, score-points-value]
           ["5 + 15" , 5+15,  1],
           ["25 - 20", 25-20, 1]
        ];

function calc() {    
  var question = QA[i][0]; 
  var answer   = QA[i][1];
  var points   = QA[i][2];  
  var correct  = answer == prompt("Question for "+ points +" points:\n"+ question );
  if(correct){
    playerScore += points;
    alert("Great! Your score is: "+ playerScore);
  }else{
   alert("Wrong, the correct answer is "+ answer ); 
  }
  calc(i++); // Move on with the game
}

calc(); // Start 

您输入了“提示”功能的名称错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM