在JavaScript数组中,我如何得到最后5个元素,不包括第一个元素?

[1, 55, 77, 88] // ...would return [55, 77, 88]

再举几个例子:

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

[1] // ...would return []

当前回答

ES6道:

我使用解构赋值数组来获得第一个和剩余的其余元素,然后我将使用slice方法获取剩余的最后五个元素:

const cutOffFirstAndLastFive = (array) => { Const[首先,…Rest] =数组; 返回rest.slice (5); } cutOffFirstAndLastFive([1,55,77,88]); console.log ( “测试:”, JSON。stringify(cutOffFirstAndLastFive([1,55,77,88])), JSON。stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])), JSON.stringify (cutOffFirstAndLastFive ([1])) );

其他回答

你可以致电:

arr.slice(Math.max(arr.length - 5, 1))

如果不想排除第一个元素,请使用

arr.slice(Math.max(arr.length - 5, 0))

试试这个:

var array = [1, 55, 77, 88, 76, 59];
var array_last_five;
array_last_five = array.slice(-5);
if (array.length < 6) {
     array_last_five.shift();
}

我还没见过比这更短的

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

运行下面的代码片段,以证明它正在执行您想要的操作

Const arr = []; 对于(设I = 0;I < 8;我+ +){ arr.push(我); console.log('数组$ {i + 1}: $ {arr} - > $ {arr.slice (1) .slice(5)}”); }

另一种方法是使用lodash https://lodash.com/docs#rest -当然,如果您不介意从浏览器中加载一个巨大的JavaScript缩小文件的话。

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

初学者的解决方案:

var givme = function(n) {
    if(n.length == 1) {
        return [];
    }
    if(n.length > 5) {
        return n.slice(n.length-5, n.length);
    }
    if(n.length <= 5) {
       return n.slice(1, n.length);
    }
}

// console.log(givme([1, 55, 77, 88, 99, 22, 33, 44]));

如果你正在使用lodash,它甚至更简单的takeRight。

_。takeRight(加勒比海盗5);