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


当前回答

更新-2021 10月27日(Chrome 97+)

Array.prototype.findLast的提案现在进入第3阶段!

以下是如何使用它:

常量数组=[1,2,3,4,5];constlast_element=array.findLast((item)=>true);console.log(last_element);

您可以在这篇V8博客文章中阅读更多内容。

您可以在“Chrome中的新功能”系列中找到更多信息。

其他回答

可以通过长度属性获取最后一项。由于数组计数从0开始,因此可以通过引用array.length-1项来拾取最后一项

常量arr=[1,2,3,4];常量last=arr[arr.length-1];console.log(最后一个);//4.

另一个选项是使用新的Array.prototype.at()方法,该方法接受一个整数值并返回该索引处的项。负整数从数组中的最后一项开始倒数,所以如果我们想要最后一项,我们只需传入-1

常量arr=[1,2,3,4];常量last=arr.at(-1);console.log(最后一个);//4.

另一个选项是使用新的findLast方法。你可以在这里看到提案

常量arr=[1,2,3,4];const last=arr.findLast(x=>true);console.log(最后一个);//4.

另一个选项是使用Array.prototype.slice()方法,该方法将数组的一部分的浅拷贝返回到新的数组对象中。

常量arr=[1,2,3,4];常量last=arr.slice(-1)[0];console.log(最后一个);//4.

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

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

对我来说,这比loc_array.slice(-1)[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);

我认为这应该很好。

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

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

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

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

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

这样既干净又高效:

let list = [ 'a', 'b', 'c' ]

(xs => xs[xs.length - 1])(list)

如果您使用Babel安装管道操作员,它将变为:

list |> (xs => xs[xs.length - 1])