以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。
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
}
就我个人而言,我会支持库波里菲奇·克里齐克拉茨的回答。如果使用嵌套数组,array[array.length-1]方法会变得非常难看。
var array = [[1,2,3], [4,5,6], [7,8,9]]
array.slice(-1)[0]
//instead of
array[array.length-1]
//Much easier to read with nested arrays
array.slice(-1)[0].slice(-1)[0]
//instead of
array[array.length-1][array[array.length-1].length-1]
2022年ECMA
使用ECMA 2022,您可以在()处获得一个新属性。要从数组或字符串中获取最后一个元素,可以在中使用负索引-1。[1,2,3].在(-1)处。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
如果您希望像arr.last这样更流畅地接收最后一项,则可以为数组对象定义自己的属性。
if(!Array.protocol.hasOwnProperty(“last”)){Object.defineProperty(Array.prototype,“last”{获取(){返回此。在(-1);}});}a=[1,2,3];console.log(a.last);
通常情况下,你不应该搞乱内置类型的原型,但这里有一个破解/快捷方式:
Object.defineProperty(Array.prototype, 'last', {
get() {
return this[this.length - 1];
}
});
这将允许所有数组对象具有最后一个属性,您可以这样使用:
const letters = ['a', 'b', 'c', 'd', 'e'];
console.log(letters.last); // 'e'
您不应该使用内置类型的原型,因为您永远不会发布新的ES版本,如果新版本使用与自定义属性相同的属性名称,则可能会发生各种中断。此外,这会使其他人很难遵循您的代码,特别是对于加入团队的人。您可以将属性设置为您知道ES版本永远不会使用的属性,例如listLastItem,但这由开发人员自行决定。
或者您可以使用一个简单的方法:
const getLast = (list) => list[list.length - 1];
const last = getLast([1,2,3]); // returns 3
以下是如何在不影响原始阵列的情况下获得它
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