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


当前回答

可以通过长度属性获取最后一项。由于数组计数从0开始,因此可以通过引用array.length-1项来拾取最后一项

常量arr=[1,2,3,4];常量last=arr[arr.length-1];console.log(最后一个);//4.

另一个选项是使用新的Array.prototype.at()方法,该方法接受一个整数值并返回该索引处的项。负整数从数组中的最后一项开始倒数,所以如果我们想要最后一项,我们只需传入-1

常量arr=[1,2,3,4];常量last=arr.at(-1);console.log(最后一个);//4.

另一个选项是使用新的findLast方法。你可以在这里看到提案

常量arr=[1,2,3,4];const last=arr.findLast(x=>true);console.log(最后一个);//4.

另一个选项是使用Array.prototype.slice()方法,该方法将数组的一部分的浅拷贝返回到新的数组对象中。

常量arr=[1,2,3,4];常量last=arr.slice(-1)[0];console.log(最后一个);//4.

其他回答

如果想要一次性获得最后一个元素,可以使用Array#splice():

lastElement = document.location.href.split('/').splice(-1,1);

这里,不需要将拆分的元素存储在数组中,然后获取最后一个元素。如果获得最后一个元素是唯一的目标,那么应该使用这个。

注意:这将通过删除最后一个元素来更改原始数组。将splice(-1,1)看作弹出最后一个元素的pop()函数。

const[lastItem]=array.sslice(-1);

带有-1的Array.prototype.slice可用于创建仅包含原始Array的最后一项的新Array,然后可以使用Destructuring Assignment使用该新Array的第一项创建变量。

常量彩票号码=[12,16,4,33,41,22];const[lastNumber]=lotteryNumbers.slice(-1);console.log(lotteryNumbers.slice(-1));// => [22]console.log(lastNumber);// => 22

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

只是在这里放了另一个选项。

loc_array.splice(-1)[0] === 'index.html'

我发现上述方法更简洁、更简短。请随意尝试一下。

注意:它将修改原始数组,如果您不想修改它,可以使用slice()

loc_array.slice(-1)[0] === 'index.html'

感谢@VinayPai指出这一点。

这行吗?

if (loc_array.pop() == "index.html"){
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-3])));
}
else{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}