以下是我迄今为止的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的比率。然而,没有人喜欢资源猪。

其他回答

在ECMAScript建议阶段1中,建议添加一个数组属性,该属性将返回最后一个元素:proposal array last。

语法:

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

可以使用polyfill。

提案作者:Keith Cirkel(chai autor)

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

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

读取-1索引已返回undefined。

编辑:

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

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

ES6对象销毁是另一种方法。

常量{length,[length-1]:last}=[1,2,3,4,5]console.log(最后一个)

使用对象析构函数从Array中提取长度属性。您可以使用按[length-1]提取的密钥创建另一个动态密钥,并将其分配给最后一个,全部在一行中。

这可以用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>

还有一个npm模块,将最后一个添加到Array.prototype

npm install array-prototype-last --save

用法

require('array-prototype-last');

[1, 2, 3].last; //=> 3 

[].last; //=> undefined