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


当前回答

简单的回答

const array = [1,2,3]
array[array.length - 1]

其他回答

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

(0)如果此一维数组

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

编辑:

最近,我又提出了一个解决方案,我现在认为这是最适合我的需求的:

function w(anArray) {
  return {
    last() {
      return anArray [anArray.length - 1];
    };
  };
}

根据上述定义,我现在可以说:

let last = w ([1,2,3]).last();
console.log(last) ; // -> 3

名称“w”代表“包装器”。您可以看到如何轻松添加更多除了“last()”之外的方法。

我说“最符合我的需要”,因为这允许我可以很容易地添加其他这样的“助手方法”任何JavaScript内置类型。发生了什么记住Lisp的car()和cdr()例子

array.reverse()[0]

太简单了

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

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

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

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