以下是我迄今为止的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 ('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
}
以下是如何在不影响原始阵列的情况下获得它
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
如果使用pop(),它将修改数组
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
但您可以使用它,这样它对原始阵列没有影响:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element