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


当前回答

这可以用lodash _.last或_.nth完成:

var数据=[1,2,3,4]var last=_.nth(数据,-1)console.log(最后一个)<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js“></script>

其他回答

“最干净”的ES6方式(IMO)是:

const foo = [1,2,3,4];
const bar = [...foo].pop();

这避免了像.pop()那样改变foo,如果我们不使用spread运算符。也就是说,我也喜欢foo.slice(-1)[0]解决方案。

const lastElement = myArray[myArray.length - 1];

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

箭头函数通过不重复数组的名称,使执行速度最快的方法更加简洁。

var lastItem = (a => a[a.length - 1])(loc_array);

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

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

const myArray = [1, 2, 3]

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