我在UI上有数组和两个按钮。我想在循环中打印Array值。我已将默认计数设置为7表示单击按钮7项目将从数组中切片并打印。
我写的逻辑是从Array中获取预期的7项,但它在到达结束时结束。
名为DOWN
的按钮将从数组的开头获取最后7个值。
和按钮'UP'将从数组后面获得最后7个值。
这就是我现在通过点击向下按钮获得的。
预期结果
它应该在永无止境的循环中运行。它应该保持重复价值。
这是fiddle
var numberOfElement =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];
var howManyelement = 7;
var up = 0;
$('.up').click(function(){
var start = numberOfElement.length - (up + howManyelement);
console.log(numberOfElement.slice(start, numberOfElement.length - (up)));
up+=howManyelement;
})
var down = 0;
$('.down').click(function(){
var start = 0 + down;
console.log(numberOfElement.slice(start, down + howManyelement));
down+=howManyelement;
})
答案 0 :(得分:1)
你在寻找这样的东西吗?
// Setup
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];
var arrIndex = 0;
function getValues(length) {
// Slice the array from our current index to the current index + the requested length
var values = arr.slice(arrIndex, arrIndex + length);
var valueCount = values.length;
// Make sure we keep adding the length of values to arrIndex so we pull new values
arrIndex += valueCount;
if (valueCount < length) {
arrIndex = 0;
// Figure out how many extra values we need and add it to the returned values
return values.concat( getValues(length - valueCount) );
} else if (arrIndex >= arr.length) {
// We have just printed the last item in the array - let's reset the index
arrIndex = 0;
}
return values;
}
// Get the values
for (var i = 0; i < 10; i++) {
console.log( getValues(7) );
}