以下是我迄今为止的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.pop()而不是索引。

while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

通过这种方式,您总是得到index.html之前的元素(假设您的数组将index.html作为一个项目)。注意:您将丢失数组中的最后一个元素。

其他回答

为了获得一个可读且简洁的解决方案,可以使用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);
if (loc_array[loc_array.length - 1] === 'index.html') {
   // do something
} else {
   // something else
}

如果您的服务器为“index.html”和“index.html”提供相同的文件,您也可以使用:.toLowerCase()。

不过,如果可能的话,您可能会考虑在服务器端做这件事:它会更干净,适用于没有JS的人。


编辑-ES-2022

使用ES-2022 Array.at(),上面的内容可以这样写:

if (loc_array.at(-1) === 'index.html') {
   // do something
} else {
   // something else
}

这行吗?

if (loc_array.pop() == "index.html"){
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-3])));
}
else{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}

使用ES6/ES2015排列运算符(…),可以执行以下操作。

常量数据=[1,2,3,4]const[last]=[…data].reverse()console.log(最后一个)

请注意,使用扩展运算符和反转,我们没有对原始数组进行变异,这是获取数组最后一个元素的纯方法。

要防止从原始阵列中删除最后一项,可以使用

Array.from(myArray).pop()

主要支持所有浏览器(ES6)