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


当前回答

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

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

读取-1索引已返回undefined。

编辑:

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

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

其他回答

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。

通常情况下,你不应该搞乱内置类型的原型,但这里有一个破解/快捷方式:

Object.defineProperty(Array.prototype, 'last', {
  get() {
    return this[this.length - 1]; 
  }
});

这将允许所有数组对象具有最后一个属性,您可以这样使用:

const letters = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.last); // 'e'

您不应该使用内置类型的原型,因为您永远不会发布新的ES版本,如果新版本使用与自定义属性相同的属性名称,则可能会发生各种中断。此外,这会使其他人很难遵循您的代码,特别是对于加入团队的人。您可以将属性设置为您知道ES版本永远不会使用的属性,例如listLastItem,但这由开发人员自行决定。

或者您可以使用一个简单的方法:

const getLast = (list) => list[list.length - 1];
const last = getLast([1,2,3]); // returns 3

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

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

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

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

如果想要一次性获得最后一个元素,可以使用Array#splice():

lastElement = document.location.href.split('/').splice(-1,1);

这里,不需要将拆分的元素存储在数组中,然后获取最后一个元素。如果获得最后一个元素是唯一的目标,那么应该使用这个。

注意:这将通过删除最后一个元素来更改原始数组。将splice(-1,1)看作弹出最后一个元素的pop()函数。