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


当前回答

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

这是我的选择

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

!问候语

其他回答

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

根据ES2022,您可以使用Array.at()方法,该方法获取一个整数值并返回该索引处的项。允许正整数和负整数。负整数从数组中的最后一项开始倒数。

演示:

const href='www.abc.com/main/index.html';constloc_array=href.split('/');//要访问数组中的元素,我们可以使用array.at()console.log(loc_array.at(-1));//这将返回最后一个索引处的项目。

const[lastItem]=array.sslice(-1);

带有-1的Array.prototype.slice可用于创建仅包含原始Array的最后一项的新Array,然后可以使用Destructuring Assignment使用该新Array的第一项创建变量。

常量彩票号码=[12,16,4,33,41,22];const[lastNumber]=lotteryNumbers.slice(-1);console.log(lotteryNumbers.slice(-1));// => [22]console.log(lastNumber);// => 22

您可以向Array原型添加last()函数。

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

编辑:

您可以使用符号来避免与其他代码不兼容:

const last=符号('last');Array.prototype〔last〕=函数(){返回this.length-1];};console.log([0,1][last]());

您可以使用此模式。。。

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

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