这个数组如何工作?

时间:2016-10-01 18:13:18

标签: javascript arrays function

只需按照简单的javascript测验。下面的代码有效,但我有一些问题。

var player = prompt("Hello, welcome to the quiz, what is your name?");
var score = 0;

var questions = [
    ["What is my name?", "Joe"],
    ["What is my age?", 27],
    ["What is my favourite sport?", "Football"],
    ["What is my job?", "Web Developer"],
    ["What is my eye color?", "Blue"]
];

function askQuestions(question) {
 var answer = prompt(question[0],'');
 if(answer === question[1]) {
     alert('Correct!')
 } else {
     alert('Wrong!');
 }
};

for(var i= 0; i < questions.length; i++) {
    askQuestions(questions[i]);
};

所以我不明白的第一件事是在askQuestions函数中,提示有问题[0]&#39;。我知道我们有一个循环,但这不是循环的一部分吗?所以这个变量肯定只是将第一个数组存储在问题变量中。

第二个参数是一个空字符串&#39;&#39;。这只是存储答案吗?这有什么作用?

我理解休息只是遇到了这个功能的问题。

如果有人能解释那会很棒!

干杯

2 个答案:

答案 0 :(得分:1)

var questions是一个2D数组的数组,每个2D数组都在循环中传递给askQuestion。然后,例如,当您在第一个循环中将问题[0]传递给askQuestion时,您实际上正在传递对象['我的名字是什么','乔']

内部函数askQuestion你将获取参数数组的第一个元素(所以,'我叫什么名字'),并将答案与参数数组的第二个元素进行比较(所以,'Joe')

也许如果您以这种方式编写askQuestion,您将了解更多工作流程:

function askQuestions(**paramArray**) {
  var answer = prompt(**paramArray**[0],'');
  if(answer === **paramArray**[1]) {
    alert('Correct!')
  } else {
    alert('Wrong!');
  }
};

关于提示,第二个参数它只是要显示的默认文本。

答案 1 :(得分:1)

所以最好的方法是看看发生了什么,只需拿走变量,然后自己插上。

askQuestions(问题[<强> I ])

插入i:

askQuestions(的问题[0]

插入问题[0]

askQuestions( [“我叫什么名字?”,“乔”]

插入功能

function askQuestions(["What is my name?", "Joe"]) {
 var answer = prompt("What is my name?",'');
 if(answer === "Joe") {
     alert('Correct!')
 } else {
     alert('Wrong!');
 }
};

我在这里评论了代码:

//player inputs their name and it is stored in var player
var player = prompt("Hello, welcome to the quiz, what is your name?");
//set var score to 0;
var score = 0;

//questions is an array, of arrays. so questions[0] is ["What is my name?", "Joe"] and questions[0][0] is "What is my name?" 
var questions = [
["What is my name?", "Joe"],
["What is my age?", 27],
["What is my favourite sport?", "Football"],
["What is my job?", "Web Developer"],
["What is my eye color?", "Blue"]
];

//askQuestions is a function that will be called in the for loop below
function askQuestions(question) {
 //set var answer to whatever the user types in, pop up will say whatever question[0] is Or in this case question[i][0] because we pass in question[i]
 var answer = prompt(question[0],'');
 //here we just check if what they type in is the same as the answer we expect
 if(answer === question[1]) {
 alert('Correct!')
 } else {
     alert('Wrong!');
 }
};

//this loop is going to to run for the questions.length, in this case 5 times, and each time it will call askQuestions(question[0]) then askQuestions(question[1]) etc
for(var i= 0; i < questions.length; i++) {
   askQuestions(questions[i]);
};

希望有帮助......:)