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

前端 未结 30 1276

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:20

    It can also be achieved using map method.

    [1, 2, 3].map((value, index, arr) => arr[arr.length - index - 1])); // [3, 2, 1]
    

    Or using reduce (little longer approach)

    [1, 2, 3].reduce((acc, curr, index, arr) => {
        acc[arr.length - index - 1] = curr;
        return acc;
    }, []);
    

提交回复
热议问题