首页 > 解决方案 > JS - 比较两个数组中的两个值似乎不起作用

问题描述

任何人都可以帮我解决这个代码:

    
var questions =[
  ['how many states?', 1],
  ['how many continents?', 2],
  ['how many legs?', 3]
]

var answers = [];
var rightAnswers = [];
var wrongAnswers = [];


for(i = 0; i<questions.length; i+=1){  
  answers.push(prompt(questions[i][0]).toLowerCase());
  
  if(questions[i][1] === answers[i]){
     // rightAnswers.push(questions[i][0]) 
     console.log("success!");
  }else{
     console.log("bummer");
  }
  
}

比较两个数组的两个插槽似乎不起作用:(谢谢!

标签: javascriptarrays

解决方案


prompt方法返回字符串,而您的答案是数字。===只需通过将严格替换为 来让松散比较完成工作==

    
var questions =[
  ['how many states?', 1],
  ['how many continents?', 2],
  ['how many legs?', 3]
]

var answers = [];
var rightAnswers = [];
var wrongAnswers = [];


for(i = 0; i<questions.length; i+=1){  
  answers.push(prompt(questions[i][0]).toLowerCase());
  
  if(questions[i][1] == answers[i]){
     // rightAnswers.push(questions[i][0]) 
     console.log("success!");
  }else{
     console.log("bummer");
  }
  
}


推荐阅读