How can I reverse an array in JavaScript without using libraries?

前端 未结 30 1207

I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can\'t think of any possible method, so if anybo

30条回答
  •  情歌与酒
    2020-11-27 06:34

    Here is a version which does not require temp array.

    function inplaceReverse(arr) {
      var i = 0;
      while (i < arr.length - 1) {
        arr.splice(i, 0, arr.pop());
        i++;
      }
      return arr;
    }
    
    // Useage:
    var arr = [1, 2, 3];
    console.log(inplaceReverse(arr)); // [3, 2, 1]
    

提交回复
热议问题