以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。


当前回答

在ECMAScript建议阶段1中,建议添加一个数组属性,该属性将返回最后一个元素:proposal array last。

语法:

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

可以使用polyfill。

提案作者:Keith Cirkel(chai autor)

其他回答

以下内容如何:

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 
}

我认为这应该很好。

var arr = [1, 2, 3];
var last_element = arr.reverse()[0];

只需反转数组并获得第一个元素。

编辑:如下所述,原始阵列将被反转。为了避免这种情况,您可以将代码更改为:

var arr = [1, 2, 3];
var last_element = arr.slice().reverse()[0];

这将创建原始阵列的副本。

为了获得一个可读且简洁的解决方案,可以使用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);

您也可以在不从url中提取数组的情况下实现此问题

这是我的选择

var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();

!问候语

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
}