这个数组是如何工作的

How does this array work?

本文关键字:工作 何工作 数组      更新时间:2023-09-26

只是遵循一个简单的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函数提示有'questions[0]'。我知道我们有一个循环,但这不是循环的一部分,对吧?显然,这个变量只是将第一个数组存储在questions变量中。

第二个参数是一个空字符串"。这只是存储答案吗?这是怎么做到的呢?

我理解rest只是在功能上有问题。

如果有人能解释一下那就太好了!

欢呼

var questions是一个2D数组的数组,每个2D数组都在循环中传递给askQuestion。然后,例如,当你在第一个循环中将问题[0]传递给askQuestion时,你实际上是在传递对象['What is my name','Joe']

在函数askQuestion中,你将选择参数数组的第一个元素(所以,'我的名字是什么'),并将答案与参数数组的第二个元素(所以,'Joe')进行比较

也许如果你这样写askQuestion,你会更了解工作流程:

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

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

所以看发生了什么,最好的方法就是取变量,自己代入。

askquestion(问题[])

插入i:

askquestion (问题[0])

插入问题[0]

askquestion (("我的名字是什么?","乔"])

插入函数

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]);
};

希望能帮到你…:)