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


当前回答

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

其他回答

在ECMAScript建议阶段1中,建议添加一个数组属性,该属性将返回最后一个元素:proposal array last。

语法:

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

可以使用polyfill。

提案作者:Keith Cirkel(chai autor)

两个选项是:

var last = arr[arr.length - 1]

or

var last = arr.slice(-1)[0]

前者更快,但后者看起来更好

http://jsperf.com/slice-vs-length-1-arr

const [y] = x.slice(-1)

快速解释:这种语法[y]=<array/object>被称为destructuring赋值&根据Mozilla文档,destructoring赋值可以将数组中的值或对象中的财产解包为不同的变量阅读更多信息:此处

另一个仅限ES6的选项是使用Array.find(item,index)=>{…}),如下所示:

const arr = [1, 2, 3];
const last = arr.find((item, index) => index === arr.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 
}