感谢这个伟大的网站使用来自Nope的优秀代码,我得到了这个代码:
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
var loopByX = function(x){
var y = myStringArray.splice(0,x);
myStringArray = myStringArray.concat(y);
return y;
}
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
这很好用...我把它添加到HTML5应用程序,看到我有一点错误描述输出的例子,所以我需要得到这个输出:
1
2
3
2
3
4
3
4
5
4
5
6
5
6
7
6
7
8
7
8
9
8
9
10
9
10
1
10
1
2
1
2
3
所以要使用上面的代码得到减去一个或一个以上的值(按向上或向下按钮,所以它被称为双向)我得到3个项目向上或向下它工作..但我看到当我复制粘贴我需要的代码在循环中获取一个项目...如果可以修改代码来完成...我尝试在函数和y-1中执行x-1但是它不会给我上面的示例输出。 ..
所以我需要函数,我可以调用loopByX(3)和多个调用函数它将在循环中左移一个位置并调用多个函数loopByX(-3)在循环中向右移动一个位置...需要什么被修改为高于输出?
非常感谢。
答案 0 :(得分:1)
您可以使用双数组和调整后的索引。
function take(direction) {
index += direction + array.length;
index %= array.length;
console.log(array.concat(array).slice(index, index + 3).join(' '));
}
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
index = 0;
<button onclick="take(-1)">-</button>
<button onclick="take(1)">+</button>
使用<div> ... </div>
function take(direction) {
index += direction + array.length;
index %= array.length;
console.log(
array
.concat(array)
.slice(index, index + 3)
.map(v => `<div>${ v }</div>`)
.join('')
);
}
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
index = 0;
<button onclick="take(-1)">-</button>
<button onclick="take(1)">+</button>