In a javascript array, how do I get the last 5 elements, excluding the first element?

前端 未结 6 1942
自闭症患者
自闭症患者 2020-11-30 20:19
[1, 55, 77, 88] // ...would return [55, 77, 88]

adding additional examples:

[1, 55, 77, 88, 99, 22, 33, 44] // ...wo         


        
6条回答
  •  长情又很酷
    2020-11-30 20:30

    Here is one I haven't seen that's even shorter

    arr.slice(1).slice(-5)

    Run the code snippet below for proof of it doing what you want

    var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],
      arr2 = [0, 1, 2, 3];
    
    document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '
    ARRAY 2: ' + arr2.slice(1).slice(-5);

    Another way to do it would be using lodash https://lodash.com/docs#rest - that is of course if you don't mind having to load a huge javascript minified file if your trying to do it from your browser.

    _.slice(_.rest(arr), -5)

提交回复
热议问题