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

前端 未结 30 1178

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

    Javascript has a reverse() method that you can call in an array

    var a = [3,5,7,8];
    a.reverse(); // 8 7 5 3
    

    Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()

    function reverseArr(input) {
        var ret = new Array;
        for(var i = input.length-1; i >= 0; i--) {
            ret.push(input[i]);
        }
        return ret;
    }
    
    var a = [3,5,7,8]
    var b = reverseArr(a);
    

    Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.

提交回复
热议问题