以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。
以下是如何在不影响原始阵列的情况下获得它
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
为了获得一个可读且简洁的解决方案,可以使用Array.prototype.slice和destructuring的组合。
const linkElement = document.getElementById("BackButton");
const loc_array = document.location.href.split('/');
// assign the last three items of the array to separate variables
const [thirdLast, secondLast, last] = loc_array.slice(-3);
// use the second last item as the slug...
let parentSlug = secondLast;
if (last === 'index.html') {
// ...unless this is an index
parentSlug = thirdLast;
}
const newT = document.createTextNode(
unescape(
capWords(parentSlug)
)
);
linkElement.appendChild(newT);
但为了简单地获取数组中的最后一项,我更喜欢这种表示法:
const [lastItem] = loc_array.slice(-1);