以下是我迄今为止的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 myArray = [1, 2, 3]

console.log(myArray.at(-1))
// => 3

其他回答

您可以向Array原型添加last()函数。

Array.prototype.last = function () {
    return this[this.length - 1];
};

编辑:

您可以使用符号来避免与其他代码不兼容:

const last=符号('last');Array.prototype〔last〕=函数(){返回this.length-1];};console.log([0,1][last]());

if (loc_array[loc_array.length - 1] === 'index.html') {
   // do something
} else {
   // something else
}

如果您的服务器为“index.html”和“index.html”提供相同的文件,您也可以使用:.toLowerCase()。

不过,如果可能的话,您可能会考虑在服务器端做这件事:它会更干净,适用于没有JS的人。


编辑-ES-2022

使用ES-2022 Array.at(),上面的内容可以这样写:

if (loc_array.at(-1) === 'index.html') {
   // do something
} else {
   // something else
}

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

(0)如果此一维数组

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

以下内容如何:

if ('index.html' === array[array.length - 1]) {  
   //do this 
} else { 
   //do that 
}

如果使用Undercore或Lodash,则可以使用_.last(),例如:

if ('index.html' === _.last(array)) {  
   //do this 
} else { 
   //do that 
}

或者您可以创建自己的最后一个函数:

const _last = arr => arr[arr.length - 1];

并像这样使用:

if ('index.html' === _last(array)) {  
   //do this 
} else { 
   //do that 
}

这可以用lodash _.last或_.nth完成:

var数据=[1,2,3,4]var last=_.nth(数据,-1)console.log(最后一个)<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js“></script>