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


当前回答

您可以向Array原型添加last()函数。

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

编辑:

您可以使用符号来避免与其他代码不兼容:

const last=符号('last');Array.prototype〔last〕=函数(){返回this.length-1];};console.log([0,1][last]());

其他回答

var str = ["stackoverflow", "starlink"];
var last = str[str.length-1];//basically you are putting the last index value into the array and storing it in la

不确定是否存在缺陷,但这似乎相当简洁:

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

如果数组为空,则两者都将返回undefined。

您可以向Array原型添加last()函数。

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

编辑:

您可以使用符号来避免与其他代码不兼容:

const last=符号('last');Array.prototype〔last〕=函数(){返回this.length-1];};console.log([0,1][last]());

无论你做什么,不要只使用reverse()!!!

一些答案提到了reverse,但没有提到reverse修改了原始数组,并且不会返回副本(在其他一些语言或框架中)。

var animals = ['dog', 'cat'];

animals.reverse()[0]
"cat"

animals.reverse()[0]
"dog"

animals.reverse()[1]
"dog"

animals.reverse()[1]
"cat"

这可能是要调试的最糟糕的代码类型!

这行吗?

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])));
}