以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。
如果想要一次性获得最后一个元素,可以使用Array#splice():
lastElement = document.location.href.split('/').splice(-1,1);
这里,不需要将拆分的元素存储在数组中,然后获取最后一个元素。如果获得最后一个元素是唯一的目标,那么应该使用这个。
注意:这将通过删除最后一个元素来更改原始数组。将splice(-1,1)看作弹出最后一个元素的pop()函数。
这个问题已经存在了很长一段时间,所以我很惊讶没有人提到在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的比率。然而,没有人喜欢资源猪。
为了获得一个可读且简洁的解决方案,可以使用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);
您可以在Array的原型中添加一个新的属性getter,以便它可以通过Array的所有实例访问。
Getters允许您访问函数的返回值,就像它是属性的值一样。函数的返回值当然是数组的最后一个值(this[this.length-1])。
最后,将其包装在一个条件中,该条件检查最后一个属性是否仍然未定义(未由可能依赖它的另一个脚本定义)。
Object.defineProperty(Array.prototype, 'last', {
get : function() {
return this[this.length - 1];
}
});
// Now you can access it like
[1, 2, 3].last; // => 3
// or
var test = [50, 1000];
alert(test.last); // Says '1000'
IE≤8时不工作。