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


当前回答

还有一个npm模块,将最后一个添加到Array.prototype

npm install array-prototype-last --save

用法

require('array-prototype-last');

[1, 2, 3].last; //=> 3 

[].last; //=> undefined 

其他回答

更新-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中的新功能”系列中找到更多信息。

使用ES6/ES2015排列运算符(…),可以执行以下操作。

常量数据=[1,2,3,4]const[last]=[…data].reverse()console.log(最后一个)

请注意,使用扩展运算符和反转,我们没有对原始数组进行变异,这是获取数组最后一个元素的纯方法。

要使用c#访问数组中的最后一个元素,我们可以使用GetUpperBound(0)

(0)如果此一维数组

my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array

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

这是我的选择

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

!问候语

var str = ["stackoverflow", "starlink"];
var last = str[str.length-1];//basically you are putting the last index value into the array and storing it in la