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


当前回答

两个选项是:

var last = arr[arr.length - 1]

or

var last = arr.slice(-1)[0]

前者更快,但后者看起来更好

http://jsperf.com/slice-vs-length-1-arr

其他回答

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

在javascript中查找数组最后一个值的多种方法

不影响原始阵列

var arr=[1,2,3,4,5];控制台日志(arr.slice(-1)[0])控制台日志(arr[arr.length-1])const[last]=[…arr].reverse();console.log(最后一个)让copyArr=[…arr];console.log(copyArr.reverse()[0]);

修改原始阵列

var arr=[1,2,3,4,5];console.log(arr.pop())arr.push(5)console.log(…arr.splice(-1));

通过创建自己的助手方法

设arr=[1,2,3,4,5];Object.defineProperty(arr,'last',{get:function(){返回this[this.length-1];}})控制台日志(arr.last);

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

演示:

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

2022年ECMA

使用ECMA 2022,您可以在()处获得一个新属性。要从数组或字符串中获取最后一个元素,可以在中使用负索引-1。[1,2,3].在(-1)处。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at

如果您希望像arr.last这样更流畅地接收最后一项,则可以为数组对象定义自己的属性。

if(!Array.protocol.hasOwnProperty(“last”)){Object.defineProperty(Array.prototype,“last”{获取(){返回此。在(-1);}});}a=[1,2,3];console.log(a.last);

为了获得一个可读且简洁的解决方案,可以使用Array.prototype.slice和destructuring的组合。

const linkElement = document.getElementById("BackButton");
const loc_array = document.location.href.split('/');

// assign the last three items of the array to separate variables
const [thirdLast, secondLast, last] = loc_array.slice(-3);

// use the second last item as the slug...
let parentSlug = secondLast;

if (last === 'index.html') {
  // ...unless this is an index
  parentSlug = thirdLast;
}

const newT = document.createTextNode(
  unescape(
    capWords(parentSlug)
  )
);

linkElement.appendChild(newT);

但为了简单地获取数组中的最后一项,我更喜欢这种表示法:

const [lastItem] = loc_array.slice(-1);