以下是我迄今为止的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

其他回答

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

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 

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

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

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

更新-2021 10月27日(Chrome 97+)

Array.prototype.findLast的提案现在进入第3阶段!

以下是如何使用它:

常量数组=[1,2,3,4,5];constlast_element=array.findLast((item)=>true);console.log(last_element);

您可以在这篇V8博客文章中阅读更多内容。

您可以在“Chrome中的新功能”系列中找到更多信息。

可以在以下位置使用数组#的相对索引:

const myArray = [1, 2, 3]

console.log(myArray.at(-1))
// => 3

我认为这应该很好。

var arr = [1, 2, 3];
var last_element = arr.reverse()[0];

只需反转数组并获得第一个元素。

编辑:如下所述,原始阵列将被反转。为了避免这种情况,您可以将代码更改为:

var arr = [1, 2, 3];
var last_element = arr.slice().reverse()[0];

这将创建原始阵列的副本。