如何打印N没有。每次点击时阵列的元素 [英] How to print N no. Of elements of array each time on click
本文介绍了如何打印N没有。每次点击时阵列的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<pre>I have an array of 20 elements. I want to display first five elements on click of a button, then next five elements on another click, and so on. I would be grateful if you could help me with the code.
I know my approach is wrong, but what I have tried displays the result two times correctly but not the third time.
我的尝试:
What I have tried:
<body>
<button onclick="nextElems();"> Try </button>
<div id="yes"> </div>
</body>
var words = ["day", "white", "go", "low", "wise", "up", "sit", "now",
"good", "grapes", "banana",
"mango", "orange", "pears", "melon", "guava", "sunflower", "marigold",
"jasmine", "sunflower"];
var x = "";
var count = 0;
function nextElems() {
if (count < words.length) {
var newArray = words.slice(0, 5);
x += '<div>' + newArray + '</div>';
document.getElementById('yes').innerHTML = x;
count = newArray;
} else {
count = 0;
var secondArray = words.slice(5, 10);
x += '<div>' + secondArray + '</div>';
document.getElementById('yes').innerHTML = x;
}
x = "";
}
推荐答案
使用队列或堆栈,取决于您想要返回它们的顺序。
您可以一次出列或弹出5,而无需跟踪。
数据结构 - 如何实施JavaScript中的堆栈和队列? - 堆栈溢出 [ ^ ]
Use a Queue or a Stack, depends on what order you want to return them.
You can then "dequeue" or "pop" 5 at a time, without having to keep track.
data structures - How do you implement a Stack and a Queue in JavaScript? - Stack Overflow[^]
这篇关于如何打印N没有。每次点击时阵列的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文