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


当前回答

箭头函数通过不重复数组的名称,使执行速度最快的方法更加简洁。

var lastItem = (a => a[a.length - 1])(loc_array);

其他回答

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' ] ] ]

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

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

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

简单的回答

const array = [1,2,3]
array[array.length - 1]
if (loc_array[loc_array.length - 1] === 'index.html') {
   // do something
} else {
   // something else
}

如果您的服务器为“index.html”和“index.html”提供相同的文件,您也可以使用:.toLowerCase()。

不过,如果可能的话,您可能会考虑在服务器端做这件事:它会更干净,适用于没有JS的人。


编辑-ES-2022

使用ES-2022 Array.at(),上面的内容可以这样写:

if (loc_array.at(-1) === 'index.html') {
   // do something
} else {
   // something else
}

如果你来这里找的话,这里还有更多的Javascript艺术

根据另一个使用reduceRight()但更短的答案:

[3, 2, 1, 5].reduceRight(a => a);

它依赖于这样一个事实,即如果您没有提供初始值,最后一个元素将被选为初始元素(请查看此处的文档)。由于回调只返回初始值,最后一个元素将是最后返回的元素。

请注意,这应该被认为是Javascript的艺术,而不是我推荐的方式,主要是因为它在O(n)时间运行,但也因为它会损害可读性。

现在是严肃的答案

我认为最好的方法(考虑到您希望它比array[array.length-1]更简洁)是:

const last = a => a[a.length - 1];

然后只需使用函数:

last([3, 2, 1, 5])

如果您正在处理上面使用的[3,2,1,5]这样的匿名数组,则该函数实际上非常有用,否则您必须将其实例化两次,这将是低效且丑陋的:

[3, 2, 1, 5][[3, 2, 1, 5].length - 1]

Ugh.

例如,在这种情况下,您有一个匿名数组,您必须定义一个变量,但您可以使用last()代替:

last("1.2.3".split("."));