以下是我迄今为止的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中的新功能”系列中找到更多信息。

其他回答

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

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

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

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

读取-1索引已返回undefined。

编辑:

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

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

您可以使用此模式。。。

let [last] = arr.slice(-1);

虽然它读起来很好,但请记住,它创建了一个新的阵列,因此效率比其他解决方案低,但它几乎永远不会成为应用程序的性能瓶颈。

2020年更新

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

let a = [1, 2, 3, [4, 5]];

console.log(a.last());
// [ 4, 5 ]
console.log(a.last().last());
// 5

沉降器和集尘器

Array.prototype.last = function(val=null) {
  if (this.length === 0) {
    if (val) this[0] = val;
    else return null; 
  }
  
  temp = this;
  while(typeof temp[temp.length-1] === "object") {
    temp = temp[temp.length-1];
  }
  
  if (val) temp[temp.length-1] = val; //Setter  
  else return temp[temp.length-1]; //Getter
  
}

var arr = [[1, 2], [2, 3], [['a', 'b'], ['c', 'd']]];
console.log(arr.last()); // 'd'
    
arr.last("dd"); 
console.log(arr); // [ [ 1, 2 ], [ 2, 3 ], [ [ 'a', 'b' ], [ 'c', 'dd' ] ] ]

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

npm install array-prototype-last --save

用法

require('array-prototype-last');

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

[].last; //=> undefined