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


当前回答

这个问题已经存在了很长一段时间,所以我很惊讶没有人提到在pop()之后重新打开最后一个元素。

arr.pop()的效率与arr[arr.length-1]完全相同,两者的速度都与arr.push()相同。

因此,您可以避免:

---已编辑[在推送前检查顶部是否未定义]---

let thePop = arr.pop()
thePop && arr.push(thePop)

---结束编辑---

可以降低到这个速度(相同速度[编辑:但不安全!]):

arr.push(thePop = arr.pop())    //Unsafe if arr empty

这是arr[arr.length-1]的两倍慢,但您不必到处填充索引。这在任何一天都是值得的。

在我尝试过的解决方案中,以arr[arr.length-1]的执行时间单位(ETU)的倍数表示:

[方法]。。。。。。。。。。。。。。[ETU 5元素]。。。[ETU 100万元]

arr[arr.length - 1]      ------> 1              -----> 1

let myPop = arr.pop()
arr.push(myPop)          ------> 2              -----> 2

arr.slice(-1).pop()      ------> 36             -----> 924  

arr.slice(-1)[0]         ------> 36             -----> 924  

[...arr].pop()           ------> 120            -----> ~21,000,000 :)

最后三个选项,特别是[…arr].pop(),随着数组大小的增加,会变得非常糟糕。在没有我的机器内存限制的机器上,[…arr].pop()可能会保持120:1的比率。然而,没有人喜欢资源猪。

其他回答

jQuery巧妙地解决了这个问题:

> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined

@chaiguy发布内容的简短版本:

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

读取-1索引已返回undefined。

编辑:

如今,人们倾向于使用模块,避免接触原型或使用全局命名空间。

export function last(array) {
    return array[array.length - 1];
}

这行吗?

if (loc_array.pop() == "index.html"){
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-3])));
}
else{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}

您可以向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]());

“最干净”的ES6方式(IMO)是:

const foo = [1,2,3,4];
const bar = [...foo].pop();

这避免了像.pop()那样改变foo,如果我们不使用spread运算符。也就是说,我也喜欢foo.slice(-1)[0]解决方案。