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


当前回答

为了获得一个可读且简洁的解决方案,可以使用Array.prototype.slice和destructuring的组合。

const linkElement = document.getElementById("BackButton");
const loc_array = document.location.href.split('/');

// assign the last three items of the array to separate variables
const [thirdLast, secondLast, last] = loc_array.slice(-3);

// use the second last item as the slug...
let parentSlug = secondLast;

if (last === 'index.html') {
  // ...unless this is an index
  parentSlug = thirdLast;
}

const newT = document.createTextNode(
  unescape(
    capWords(parentSlug)
  )
);

linkElement.appendChild(newT);

但为了简单地获取数组中的最后一项,我更喜欢这种表示法:

const [lastItem] = loc_array.slice(-1);

其他回答

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

表演

今天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结果示例

根据ES2022,您可以使用Array.at()方法,该方法获取一个整数值并返回该索引处的项。允许正整数和负整数。负整数从数组中的最后一项开始倒数。

演示:

const href='www.abc.com/main/index.html';constloc_array=href.split('/');//要访问数组中的元素,我们可以使用array.at()console.log(loc_array.at(-1));//这将返回最后一个索引处的项目。

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

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