以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。
通常情况下,你不应该搞乱内置类型的原型,但这里有一个破解/快捷方式:
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
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#splice():
lastElement = document.location.href.split('/').splice(-1,1);
这里,不需要将拆分的元素存储在数组中,然后获取最后一个元素。如果获得最后一个元素是唯一的目标,那么应该使用这个。
注意:这将通过删除最后一个元素来更改原始数组。将splice(-1,1)看作弹出最后一个元素的pop()函数。
您可以在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时不工作。