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

其他回答

您也可以在不从url中提取数组的情况下实现此问题

这是我的选择

var hasIndex = (document.location.href.search('index.html') === -1) ? doSomething() : doSomethingElse();

!问候语

要使用c#访问数组中的最后一个元素,我们可以使用GetUpperBound(0)

(0)如果此一维数组

my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array

表演

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

以下是如何在不影响原始阵列的情况下获得它

a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements

如果使用pop(),它将修改数组

a.pop();  // will return "abc" AND REMOVES IT from the array 
a.length; // returns 7

但您可以使用它,这样它对原始阵列没有影响:

a.slice(-1).pop(); // will return "abc" won't do modify the array 
                   // because slice creates a new array object 
a.length;          // returns 8; no modification and you've got you last element 

我宁愿使用array.pop()而不是索引。

while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));

通过这种方式,您总是得到index.html之前的元素(假设您的数组将index.html作为一个项目)。注意:您将丢失数组中的最后一个元素。