2015-03-25 56 views
-1

顯示元件I具有包含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()顯示,然後再次單擊該按鈕時,我想顯示第二個元素,直到通過單擊該按鈕顯示了所有元素。

例如,我曾嘗試使用該按鈕的點擊數財產與一個for循環一起,試圖讓這個問題顯示如下所示的JSFiddle

但是這顯示所有的問題在點擊一下數組。

感謝

+0

編程中的「不確定」可以通過嘗試和嘗試輕鬆兌換。 – Xufox 2015-03-25 12:52:28

+1

你不需要使用循環。你有理由不得不打電話問題[我],我是這個人點擊按鈕的次數。 – Unex 2015-03-25 12:52:47

回答

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; 
2

可能不是你想要什麼,但這裏有一個開始

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

所有的問題都得到了回答後,就可以看到答案

console.log(answers); 
+1

哇,這是一個使用'map'和'prompt'的美麗方式。 – Xufox 2015-03-25 12:56:10

+0

@xufox爲什麼感謝你^。^ – naomik 2015-03-25 13:02:49

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

http://jsfiddle.net/vjvkvjas/2/

你可能喜歡的東西

var answers=[]; 
btn.addEventListener('click',function(){ 
    if(questions.length){ 
    answers.push(prompt(questions.pop().question)); 
    } 
}); 

這是沒有任何計數變量緊湊的解決方案進行試驗。代替popshift也是可能的。