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


当前回答

这行吗?

if (loc_array.pop() == "index.html"){
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-3])));
}
else{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}

其他回答

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

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

读取-1索引已返回undefined。

编辑:

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

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

更新-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中的新功能”系列中找到更多信息。

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

(0)如果此一维数组

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

通过使用带负值的切片方法可以获得数组的最后一项。

你可以在底部阅读更多关于它的信息。

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

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

简单的回答

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