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


当前回答

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

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

其他回答

通过使用带负值的切片方法可以获得数组的最后一项。

你可以在底部阅读更多关于它的信息。

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

使用pop()将改变数组,这并不总是一个好主意。

这可以用lodash _.last或_.nth完成:

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

@chaiguy发布内容的简短版本:

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

读取-1索引已返回undefined。

编辑:

如今,人们倾向于使用模块,避免接触原型或使用全局命名空间。

export function last(array) {
    return array[array.length - 1];
}

要防止从原始阵列中删除最后一项,可以使用

Array.from(myArray).pop()

主要支持所有浏览器(ES6)

使用Ramda进行功能编程

如果你在使用JS,我建议你去看看Ramda,它是一个函数式编程库(像Lodash和Undercore,除了更高级和模块化)。Ramda提供了R.last

import * as R from 'ramda';
R.last(['fi', 'fo', 'fum']); //=> 'fum'
R.last([]); //=> undefined

R.last('abc'); //=> 'c'
R.last(''); //=> ''

它还提供了init、head和tail。列出怪物(了解你是哈斯克尔)