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


当前回答

使用Ramda进行功能编程

如果你在使用JS,我建议你去看看Ramda,它是一个函数式编程库(像Lodash和Undercore,除了更高级和模块化)。Ramda提供了R.last

import * as R from 'ramda';
R.last(['fi', 'fo', 'fum']); //=> 'fum'
R.last([]); //=> undefined

R.last('abc'); //=> 'c'
R.last(''); //=> ''

它还提供了init、head和tail。列出怪物(了解你是哈斯克尔)

其他回答

无论你做什么,不要只使用reverse()!!!

一些答案提到了reverse,但没有提到reverse修改了原始数组,并且不会返回副本(在其他一些语言或框架中)。

var animals = ['dog', 'cat'];

animals.reverse()[0]
"cat"

animals.reverse()[0]
"dog"

animals.reverse()[1]
"dog"

animals.reverse()[1]
"cat"

这可能是要调试的最糟糕的代码类型!

我通常使用underscorejs,有了它你就可以

if (_.last(loc_array) === 'index.html'){
  etc...
}

对我来说,这比loc_array.slice(-1)[0]更具语义

我宁愿使用array.pop()而不是索引。

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

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

2022年ECMA

使用ECMA 2022,您可以在()处获得一个新属性。要从数组或字符串中获取最后一个元素,可以在中使用负索引-1。[1,2,3].在(-1)处。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at

如果您希望像arr.last这样更流畅地接收最后一项,则可以为数组对象定义自己的属性。

if(!Array.protocol.hasOwnProperty(“last”)){Object.defineProperty(Array.prototype,“last”{获取(){返回此。在(-1);}});}a=[1,2,3];console.log(a.last);

这行吗?

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])));
}