以下是我迄今为止的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的选项是使用Array.find(item,index)=>{…}),如下所示:

const arr = [1, 2, 3];
const last = arr.find((item, index) => index === arr.length - 1);

没有什么实际价值,张贴出来表明索引也可用于您的过滤逻辑。

其他回答

var str = ["stackoverflow", "starlink"];
var last = str[str.length-1];//basically you are putting the last index value into the array and storing it in la

使用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>

简单的回答

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

从性能角度来看,这是最佳选项(比arr.slice(-1)快1000倍左右)。

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

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

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