Javascript向左或向右双向移位

标签 javascript shift

感谢这个伟大的网站使用了来自 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 个项目并且它有效..但是我看到当我复制粘贴我需要的代码时在循环中向上或向下获取一个项目...如果可以修改代码来做到这一点...我尝试在函数中执行 x-1 和 y-1 但它不会给我上面的示例输出。 ..

所以我需要可以调用 loopByX(3) 的函数和多个调用函数,它将在循环中向左移动一个位置并调用多个函数 loopByX(-3) 在循环中向右移动一个位置...需要什么进行修改以实现上述输出?

非常感谢。

最佳答案

您可以采用 double 组和调整后的索引。

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>

关于Javascript向左或向右双向移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50474996/

相关文章:

javascript ->>= 在 JavaScript 中如何工作

javascript - 从 vue.js 中的 foreach 循环访问变量

c 得到整数的第 n 个字节

arrays - 基于前 n 行在 groupby() 中创建新列的更短方法

python - Pandas shift - 如何保留最后一行?

javascript - jquery 相当于 getcompulatedstyle()

java - 使用 javascript 动态添加行时,我增加索引值,但出现错误

javascript - lodash 的所有键的 mapValues

c++ - 移动数组以替换删除的元素

java - JavaFX 中是否有可能获得移位字符?