【问题标题】:Javascript shif left or right bidirectionalJavascript向左或向右移动双向
【发布时间】:2018-05-22 19:16:59
【问题描述】:

感谢这个伟大的网站使用来自 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) 在循环中右移一位...需要什么修改为归档以上输出?

非常感谢。

【问题讨论】:

  • 请在点击后添加所需输出的示例。
  • 上面的例子...我将数组定义为 var myStringArray = ["1","2","3","4","5","6","7", "8","9","10"];输出为 123 234 345 等。请参见上面的示例

标签: javascript shift


【解决方案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>

&lt;div&gt; ... &lt;/div&gt;

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>

【讨论】:

  • 如何添加到每个数字
    ?比如
    2
    3
    4
    ?输出非常好,只需要添加div标签就可以完美运行
  • 谢谢..现在应用程序运行完美,速度非常快..您为我节省了很多时间搜索和测试代码...我投票支持您的答案,并且速度极快且运行良好..谢谢尼娜
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 2012-02-19
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 2011-03-29
相关资源
最近更新 更多