以下是我迄今为止的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#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
}