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


当前回答

获取数组最后一项的简单方法:

var last_item = loc_array.reverse()[0];

当然,我们需要先检查以确保数组至少有一个项。

其他回答

const lastElement = myArray[myArray.length - 1];

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

两个选项是:

var last = arr[arr.length - 1]

or

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

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

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

const [y] = x.slice(-1)

快速解释:这种语法[y]=<array/object>被称为destructuring赋值&根据Mozilla文档,destructoring赋值可以将数组中的值或对象中的财产解包为不同的变量阅读更多信息:此处

要使用c#访问数组中的最后一个元素,我们可以使用GetUpperBound(0)

(0)如果此一维数组

my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array

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

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

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