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


当前回答

使用reduceRight:

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

其他回答

这行吗?

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])));
}

通过使用带负值的切片方法可以获得数组的最后一项。

你可以在底部阅读更多关于它的信息。

var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
  //your code...
}

使用pop()将改变数组,这并不总是一个好主意。

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

使用Ramda进行功能编程

如果你在使用JS,我建议你去看看Ramda,它是一个函数式编程库(像Lodash和Undercore,除了更高级和模块化)。Ramda提供了R.last

import * as R from 'ramda';
R.last(['fi', 'fo', 'fum']); //=> 'fum'
R.last([]); //=> undefined

R.last('abc'); //=> 'c'
R.last(''); //=> ''

它还提供了init、head和tail。列出怪物(了解你是哈斯克尔)

表演

今天2020.05.16我在MacOs High Sierra v10.13.6上对Chrome v81.0、Safari v13.1和Firefox v76.0上选择的解决方案进行了测试

结论

arr[arr.length-1](D)被推荐为最快的跨浏览器解决方案可变解arr.pop()(A)和不可变的_.last(arr)(L)是快速的解I、J对于长字符串来说是慢的解决方案H、K(jQuery)在所有浏览器上都是最慢的

细节

我测试了两种解决方案:

可变的:A,BC不可变:D,EFGH我J(我的),从外部库不可变:K,LM

两种情况

短字符串-10个字符-您可以在此处运行测试长字符串-1M个字符-您可以在此处运行测试

函数A(arr){return arr.pop();}函数B(arr){返回arr.splice(-1,1);}函数C(arr){return arr.reverse()[0]}函数D(arr){返回arr[arr.length-1];}函数E(arr){返回arr.slice(-1)[0];}函数F(arr){let〔last〕=arr.slice(-1);最后返回;}函数G(arr){返回arr.slice(-1).pop();}函数H(arr){return[…arr].pop();}函数I(arr){return arr.reduceRight(a=>a);}函数J(arr){返回arr.find((e,i,a)=>a.length==i+1);}函数K(arr){return$(arr).get(-1);}函数L(arr){return _.last(arr);}函数M(arr){return _.nth(arr,-1);}// ----------//测试// ----------让loc_array=[“域”、“a”、“b”、“c”、“d”、“e”、“f”、“g”、“h”、“文件”];log=(f)=>console.log(`${f.name}:${f([…loc_array])}`);[A、B、C、D、E、F、G、H、I、J、K、L、M]。对于每个(F=>log(F));<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js“integrity=”sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=“crossrorigin=”匿名“></script>

短字符串的Chrome结果示例