如何更改数组中的位置?

How to change places in an Array?

有一个包含 5 个元素的列表。默认情况下,列表(数组)应显示 ["A"、"B"、"C"、"D"、"E"]。元素应该每秒旋转一个位置:

1 秒后列表:["B", "C", "D", "E", "A"];

2 秒后:[“C”、“D”、“E”、“A”、“B”];

3 秒后:[“D”、“E”、“A”、“B”、“C”];

我正在学习,我需要帮助。你会如何解决这个问题?这是我的错误解决方案:

const testArray = ["A", "B", "C", "D", "E"];
    
    const swap = function(theArray, indexA, indexB) {
        let temp = theArray[indexA];
        theArray[indexA] = theArray[indexB];
        theArray[indexB] = temp;
    };
        
    swap(testArray, 0, 1);
    console.log(testArray);

你可以试试array.shift方法:

const arr = [1, 2, 3, 4, 5];

setInterval(() => {
  const firstElement = arr.shift();

  arr.push(firstElement);

  console.log(arr);
}, 1000);

这是交换的较短版本

    const testArray = ["A", "B", "C", "D", "E"];
    
    const swap = function(theArray) {
        theArray.push(theArray.shift())
    };
        
    swap(testArray);
    console.log(testArray);

你可以shift the first element off the array, and then push它到数组的末尾。

const arr = ['A', 'B', 'C', 'D', 'E'];

function swap(arr) {

  // Log the joined array
  console.log(arr.join(''));
  
  // `shift` the first element off the array
  // and `push` it back on
  arr.push(arr.shift());

  // Repeat by calling `swap` again after
  // one second, passing in the updated array
  setTimeout(swap, 1000, arr);

}

swap(arr);

添加文档

除了愚蠢的短之外没有任何原因。

let r = ['A','B','C','D','E'];
setInterval(_ => {r.push(r.shift());console.log(r)},1000)