以下是我迄今为止的JavaScript代码:

var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 
linkElement.appendChild(newT);

目前,它从URL中获取数组中倒数第二项。但是,我想检查数组中的最后一个项目是否为“index.html”,如果是这样,则获取倒数第三个项目。


当前回答

使用ES6/ES2015排列运算符(…),可以执行以下操作。

常量数据=[1,2,3,4]const[last]=[…data].reverse()console.log(最后一个)

请注意,使用扩展运算符和反转,我们没有对原始数组进行变异,这是获取数组最后一个元素的纯方法。

其他回答

简单的回答

const array = [1,2,3]
array[array.length - 1]

不确定是否存在缺陷,但这似乎相当简洁:

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

如果数组为空,则两者都将返回undefined。

@chaiguy发布内容的简短版本:

Array.prototype.last = function() {
    return this[this.length - 1];
}

读取-1索引已返回undefined。

编辑:

如今,人们倾向于使用模块,避免接触原型或使用全局命名空间。

export function last(array) {
    return array[array.length - 1];
}

两个选项是:

var last = arr[arr.length - 1]

or

var last = arr.slice(-1)[0]

前者更快,但后者看起来更好

http://jsperf.com/slice-vs-length-1-arr

以下是如何在不影响原始阵列的情况下获得它

a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements

如果使用pop(),它将修改数组

a.pop();  // will return "abc" AND REMOVES IT from the array 
a.length; // returns 7

但您可以使用它,这样它对原始阵列没有影响:

a.slice(-1).pop(); // will return "abc" won't do modify the array 
                   // because slice creates a new array object 
a.length;          // returns 8; no modification and you've got you last element