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


当前回答

jQuery巧妙地解决了这个问题:

> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined

其他回答

“最干净”的ES6方式(IMO)是:

const foo = [1,2,3,4];
const bar = [...foo].pop();

这避免了像.pop()那样改变foo,如果我们不使用spread运算符。也就是说,我也喜欢foo.slice(-1)[0]解决方案。

箭头函数通过不重复数组的名称,使执行速度最快的方法更加简洁。

var lastItem = (a => a[a.length - 1])(loc_array);

根据ES2022,您可以使用Array.at()方法,该方法获取一个整数值并返回该索引处的项。允许正整数和负整数。负整数从数组中的最后一项开始倒数。

演示:

const href='www.abc.com/main/index.html';constloc_array=href.split('/');//要访问数组中的元素,我们可以使用array.at()console.log(loc_array.at(-1));//这将返回最后一个索引处的项目。

您可以使用此模式。。。

let [last] = arr.slice(-1);

虽然它读起来很好,但请记住,它创建了一个新的阵列,因此效率比其他解决方案低,但它几乎永远不会成为应用程序的性能瓶颈。

我通常使用underscorejs,有了它你就可以

if (_.last(loc_array) === 'index.html'){
  etc...
}

对我来说,这比loc_array.slice(-1)[0]更具语义