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

前端 未结 30 1216

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条回答
  •  Happy的楠姐
    2020-11-27 06:25

    Reverse by using the sort method

    • This is a much more succinct method.

    const resultN = document.querySelector('.resultN');
    const resultL = document.querySelector('.resultL');
    
    const dataNum = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    const dataLetters = ['a', 'b', 'c', 'd', 'e'];
    
    const revBySort = (array) => array.sort((a, b) => a < b);
    
    resultN.innerHTML = revBySort(dataNum);
    resultL.innerHTML = revBySort(dataLetters);

提交回复
热议问题