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


当前回答

jQuery巧妙地解决了这个问题:

> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined

其他回答

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

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

读取-1索引已返回undefined。

编辑:

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

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

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

Object.defineProperty( Array.prototype, "getLast", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 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' ] ] ]

简单的回答

const array = [1,2,3]
array[array.length - 1]

以下内容如何:

if ('index.html' === array[array.length - 1]) {  
   //do this 
} else { 
   //do that 
}

如果使用Undercore或Lodash,则可以使用_.last(),例如:

if ('index.html' === _.last(array)) {  
   //do this 
} else { 
   //do that 
}

或者您可以创建自己的最后一个函数:

const _last = arr => arr[arr.length - 1];

并像这样使用:

if ('index.html' === _last(array)) {  
   //do this 
} else { 
   //do that 
}