获取数组中的最后一项 [英] Get the last item in an array

查看:32
本文介绍了获取数组中的最后一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前的 JavaScript 代码:

Here is my JavaScript code so far:

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",如果是,则改为获取倒数第三项.

Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.

推荐答案

2021 年 7 月 13 日更新

新的at() 方法 允许您使用负索引来表示从最后".

Update 13 July 2021

The new at() method allows you to use negative indices to mean "from the end".

你可以像这样访问locArray的最后一项:

You can access the last item of locArray like this:

if (locArray.at(-1) === 'index.html') {
   // do something
} else {
   // something else
}

更新时,Chrome 92+、FireFox 90+、Node 16 和 Deno 1.12+ 支持 at() 方法

At time of update, the at() method is supported in Chrome 92+, FireFox 90+, Node 16 and Deno 1.12+

if (loc_array[loc_array.length - 1] === 'index.html') {
   // do something
} else {
   // something else
}

如果您的服务器为index.html"提供相同的文件,和inDEX.html"你也可以使用:.toLowerCase().

In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().

不过,如果可能的话,您可能想考虑在服务器端执行此操作:它会更干净,并且适用于没有 JS 的人.

Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.

这篇关于获取数组中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆