以下是我迄今为止的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 fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

使用pop()将改变数组,这并不总是一个好主意。

其他回答

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

(0)如果此一维数组

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

只是在这里放了另一个选项。

loc_array.splice(-1)[0] === 'index.html'

我发现上述方法更简洁、更简短。请随意尝试一下。

注意:它将修改原始数组,如果您不想修改它,可以使用slice()

loc_array.slice(-1)[0] === 'index.html'

感谢@VinayPai指出这一点。

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

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

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

@chaiguy发布内容的简短版本:

Array.prototype.last = function() {
    return this[this.length - 1];
}

读取-1索引已返回undefined。

编辑:

如今,人们倾向于使用模块,避免接触原型或使用全局命名空间。

export function last(array) {
    return array[array.length - 1];
}

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

Array.from(myArray).pop()

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