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


当前回答

可以在以下位置使用数组#的相对索引:

const myArray = [1, 2, 3]

console.log(myArray.at(-1))
// => 3

其他回答

@chaiguy发布内容的简短版本:

Array.prototype.last = function() {
    return this[this.length - 1];
}

读取-1索引已返回undefined。

编辑:

如今,人们倾向于使用模块,避免接触原型或使用全局命名空间。

export function last(array) {
    return array[array.length - 1];
}

您可以使用此模式。。。

let [last] = arr.slice(-1);

虽然它读起来很好,但请记住,它创建了一个新的阵列,因此效率比其他解决方案低,但它几乎永远不会成为应用程序的性能瓶颈。

简单的回答

const array = [1,2,3]
array[array.length - 1]
const lastElement = myArray[myArray.length - 1];

从性能角度来看,这是最佳选项(比arr.slice(-1)快1000倍左右)。

可以通过长度属性获取最后一项。由于数组计数从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.