如何使用循环显示数组中的元素

时间:2015-03-25 12:48:55

标签: javascript loops

我有一个包含7个对象的数组,这些对象的问题如下:

var questions = [ {question: 'Which turkish club did former Leeds player Harry Kewell join in 2008, which caused an uproar amongst Leeds supporters?'}, 
            {question: 'Who is the former Liverpool star who beat Ruud Van Nistelrooy\'s record of most prolific foreign goalscorer in their debut in the Premier League?'},
             {question: 'Who scored Liverpool\'s winner in \'that\' first 4-3 game against Kevin Keegan\'s Newcastle United in April 1996?'},
             {question: 'Which club was former Leeds Unted player Eric Cantona sold to in 1992?'},
             {question: 'Which former Aston Villa and Ireland midfielder went on to become a regular TV pundit with ITV?'},
             {question: 'How many European Cups had Liverpool won up to and including 2007-8?'},
             {question: 'Name the Liverpool scorers for the \'miracle of Istanbul\'.'}
];

我希望在通过提醒功能点击按钮时使用循环显示每个问题。我只需显示已存在于数组中的问题。我不想向用户询问任何事情。因此,当单击按钮时,我只想拉出第一个元素并使用alert()显示,然后再次单击该按钮时,我想显示第二个元素,直到通过单击按钮显示所有元素。

作为示例,我尝试使用按钮的onlick属性以及for循环来尝试在JSFiddle上显示如下所示的问题:

但只需点击一下即可显示数组中的所有问题。

谢谢

4 个答案:

答案 0 :(得分:2)

可能不完全是你想要的,但这是一个开始

var answers = questions.map(function(q) { return prompt(q.question); });

在回答完所有问题后,您可以看到答案

console.log(answers);

答案 1 :(得分:0)

最简单的方法是使用计数器:

var questions = ....
var counter = 0;
function onButtonClick(){
    alert(questions[counter]['question']);
}

您可以通过使用字符串数组而不是包含字符串的对象数组来简化操作。

var questions = ['question1', 'question2'...];
var counter = 0;
function onButtonClick(){
    alert(questions[counter]);
}

如果您希望用户给您答案,可以使用prompt命令:

var questions = ['question1', 'question2'...];
var answers = new Array();
var counter = 0;
function onButtonClick(){
    answers.push(prompt(questions[counter++]['question']));
}

答案 2 :(得分:0)

你不需要循环。您只需要一个变量来跟踪按钮被点击的次数(或者像@naomik提供的答案一样神奇的单行)。

var timesClicked = 0;

onClick()方法中:

var answer = prompt(questions[timesClicked]);  // ask user a question, store the answer
if(timesClicked < questions.length)
    timesClicked++;
else  // optionally you can reset the counter after all the questions have been answered
    timesClicked = 0;

答案 3 :(得分:0)

请参阅此JSFiddle

您可以尝试类似

的内容
const answers = [];

btn.addEventListener("click", function(){
  if(questions.length){
    answers.push(prompt(questions.pop().question));
  }
});

这是一个没有任何计数变量的紧凑型解决方案。 <{1}}取代pop也是可能的。