以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。
2022年ECMA
使用ECMA 2022,您可以在()处获得一个新属性。要从数组或字符串中获取最后一个元素,可以在中使用负索引-1。[1,2,3].在(-1)处。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
如果您希望像arr.last这样更流畅地接收最后一项,则可以为数组对象定义自己的属性。
if(!Array.protocol.hasOwnProperty(“last”)){Object.defineProperty(Array.prototype,“last”{获取(){返回此。在(-1);}});}a=[1,2,3];console.log(a.last);
如果想要一次性获得最后一个元素,可以使用Array#splice():
lastElement = document.location.href.split('/').splice(-1,1);
这里,不需要将拆分的元素存储在数组中,然后获取最后一个元素。如果获得最后一个元素是唯一的目标,那么应该使用这个。
注意:这将通过删除最后一个元素来更改原始数组。将splice(-1,1)看作弹出最后一个元素的pop()函数。
以下内容如何:
if ('index.html' === array[array.length - 1]) {
//do this
} else {
//do that
}
如果使用Undercore或Lodash,则可以使用_.last(),例如:
if ('index.html' === _.last(array)) {
//do this
} else {
//do that
}
或者您可以创建自己的最后一个函数:
const _last = arr => arr[arr.length - 1];
并像这样使用:
if ('index.html' === _last(array)) {
//do this
} else {
//do that
}