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


当前回答

不确定是否存在缺陷,但这似乎相当简洁:

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

如果数组为空,则两者都将返回undefined。

其他回答

对于那些不怕重载Array原型的人(使用枚举掩码,您不应该这样做):

Object.defineProperty( Array.prototype, "getLast", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 1 ];
    }
} );

我通常使用underscorejs,有了它你就可以

if (_.last(loc_array) === 'index.html'){
  etc...
}

对我来说,这比loc_array.slice(-1)[0]更具语义

此方法不会干扰原型。它还防止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'))

您可以向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]());

我宁愿使用array.pop()而不是索引。

while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

通过这种方式,您总是得到index.html之前的元素(假设您的数组将index.html作为一个项目)。注意:您将丢失数组中的最后一个元素。