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


当前回答

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

其他回答

在ECMAScript建议阶段1中,建议添加一个数组属性,该属性将返回最后一个元素:proposal array last。

语法:

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

可以使用polyfill。

提案作者:Keith Cirkel(chai autor)

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

npm install array-prototype-last --save

用法

require('array-prototype-last');

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

[].last; //=> undefined 

为了获得一个可读且简洁的解决方案,可以使用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);

使用lodash_.last(array)获取数组的最后一个元素。

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

此方法不会干扰原型。它还防止0长度数组以及空/未定义数组。如果返回的默认值可能与数组中的项相匹配,您甚至可以重写默认值。

常量项=[1,2,3]常量noItems=[]/***返回数组中的最后一项。*如果数组为null、undefined或空,则返回默认值。*/函数arrayLast(arrayOrNull,defVal=未定义){if(!arrayOrNull | | arrayOrNull.length==0){返回defVal}return arrayOrNull[arrayOrNull.length-1]}console.log(arrayLast(项))console.log(arrayLast(noItems))console.log(arrayLast(null))console.log(arrayLast(items,'someDefault'))console.log(arrayLast(noItems,'someDefault'))console.log(arrayLast(null,'someDefault'))