以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。
在javascript中查找数组最后一个值的多种方法
不影响原始阵列
var arr=[1,2,3,4,5];控制台日志(arr.slice(-1)[0])控制台日志(arr[arr.length-1])const[last]=[…arr].reverse();console.log(最后一个)让copyArr=[…arr];console.log(copyArr.reverse()[0]);
修改原始阵列
var arr=[1,2,3,4,5];console.log(arr.pop())arr.push(5)console.log(…arr.splice(-1));
通过创建自己的助手方法
设arr=[1,2,3,4,5];Object.defineProperty(arr,'last',{get:function(){返回this[this.length-1];}})控制台日志(arr.last);
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);
为了获得一个可读且简洁的解决方案,可以使用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);