迭代循环并从数组返回字符串

时间:2016-08-05 18:47:32

标签: javascript arrays

是否有可能遍历此数组并逐个返回到数组中的HTML引号 - 每按一次按钮后?

这是我无法弄清楚的代码:

var quotes = ['"Time you enjoy wasting is not wasted time."',
'"You can have it all. Just not all at once."', 
'"They say I am old-fashioned, and live in the past, but sometimes I think
progress progresses too fast!"'];

document.getElementById("btn1").addEventListener("click", newQuote);
function newQuote(){
  for (var i = 0; i < quotes.length; i++) {
   document.getElementById("quote").innerHTML = quotes[i];  
  }
}

2 个答案:

答案 0 :(得分:1)

使用计数器跟踪下一个报价索引,并在您到达最后一个报价后将其换行:

&#13;
&#13;
var nextQuote = 0;

var quotes = [
  '"Time you enjoy wasting is not wasted time."',
  '"You can have it all. Just not all at once."',
  '"They say I am old-fashioned, and live in the past, but sometimes I think progress progresses too fast!"'
];

function newQuote() {
  document.getElementById("quote").innerHTML = quotes[nextQuote];
  nextQuote = (nextQuote + 1) % quotes.length;

}
&#13;
<div id='quote'></div>
<button onClick='newQuote()'>Next Quote</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var quotes = ['"Time you enjoy wasting is not wasted time."',
'"You can have it all. Just not all at once."', 
'"They say I am old-fashioned, and live in the past, but sometimes I think
progress progresses too fast!"'];

var quoteNumber = 0;
document.getElementById("btn1").addEventListener("click", newQuote);
function newQuote(){
  document.getElementById("quote").innerHTML = quotes[quoteNumber];
  quoteNumber++;
  if(quoteNumber == quotes.length) quoteNumber = 0;  
}