以下是我迄今为止的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.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结果示例

其他回答

对于那些不怕重载Array原型的人(使用枚举掩码,您不应该这样做):

Object.defineProperty( Array.prototype, "getLast", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 1 ];
    }
} );

为了获得一个可读且简洁的解决方案,可以使用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);

要防止从原始阵列中删除最后一项,可以使用

Array.from(myArray).pop()

主要支持所有浏览器(ES6)

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

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

获取数组最后一项的简单方法:

var last_item = loc_array.reverse()[0];

当然,我们需要先检查以确保数组至少有一个项。