【问题标题】:Adding and removing the element of an Array in a loop in javascript [closed]在javascript的循环中添加和删除数组的元素[关闭]
【发布时间】:2020-03-17 14:40:15
【问题描述】:

我有一个这样的数组:-

let arr = [1,2,3,4,5,6,7,8,9]

我想在每 20 秒后删除它的最后一个元素,然后将它添加到它自己的数组的开头,这个过程将继续并且永远不会停止

【问题讨论】:

  • so不是编码服务,你试过什么?

标签: javascript reactjs frontend


【解决方案1】:

试试

function arrayCycler(arr) {
  const newArray = [...arr];
  const lastElement = newArray.pop();
  newArray.unshift(lastElement);
  return newArray;
}

let newArray = [1,2,3,4,5,6,7,8,9]; // will be changed on every 20 seconds

setInterval(() => {
 newArray = arrayCycler(newArray);
}, 20000);

【讨论】:

    【解决方案2】:

    使用setInterval 每 20 秒更新一次列表。

    https://www.w3schools.com/jsref/met_win_setinterval.asp

    你可以使用 slice 来获取没有最后一个元素的数组。

    arr.slice(0, arr.length - 1)
    

    我会让你把它们放在一起

    【讨论】:

      【解决方案3】:

      在纯 Javascript 中

        var arr=[1,2,3,4,5,6,7];
        let circularList=setInterval( function(){
        arr.unshift(arr.pop())
        console.log(arr)
        if(arr.length==0)
           clearInterval(circularList)
        },20000);
      

      【讨论】:

        【解决方案4】:

        这是一个使用立即调用函数的示例。为了方便起见,它每秒循环一次,因此将计数器从 1000 调整为 20000

        const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        
        (function loop(arr) {
          console.log(JSON.stringify(arr));
          setTimeout(() => {
        
            // `pop` off the last element
            // and `unshift` on to the beginning
            // of the array
            arr.unshift(arr.pop());
        
            // Call `loop` again with the
            // updated array
            loop(arr);
          }, 1000);
        }(arr));

        【讨论】:

          猜你喜欢
          • 2022-01-23
          • 2012-09-14
          • 2020-10-25
          • 2018-02-02
          • 2013-05-04
          • 2012-02-15
          • 1970-01-01
          • 2017-01-30
          • 2018-05-30
          相关资源
          最近更新 更多