以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。


当前回答

要防止从原始阵列中删除最后一项,可以使用

Array.from(myArray).pop()

主要支持所有浏览器(ES6)

其他回答

要防止从原始阵列中删除最后一项,可以使用

Array.from(myArray).pop()

主要支持所有浏览器(ES6)

我宁愿使用array.pop()而不是索引。

while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

通过这种方式,您总是得到index.html之前的元素(假设您的数组将index.html作为一个项目)。注意:您将丢失数组中的最后一个元素。

2022年ECMA

使用ECMA 2022,您可以在()处获得一个新属性。要从数组或字符串中获取最后一个元素,可以在中使用负索引-1。[1,2,3].在(-1)处。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at

如果您希望像arr.last这样更流畅地接收最后一项,则可以为数组对象定义自己的属性。

if(!Array.protocol.hasOwnProperty(“last”)){Object.defineProperty(Array.prototype,“last”{获取(){返回此。在(-1);}});}a=[1,2,3];console.log(a.last);

array.reverse()[0]

太简单了

使用lodash_.last(array)获取数组的最后一个元素。

数据=[1,2,3]last=_.last(数据)console.log(最后一个)<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js“></script>