这是我到目前为止的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);
Run Code Online (Sandbox Code Playgroud)
目前,它从URL中获取数组中倒数第二个项目.但是,我想检查数组中的最后一项是"index.html",如果是,请抓住第三项到最后一项.
例如(在JavaScript中):
//Not that I would ever add a method to a base JavaScript prototype...
//(*wink nudge*)...
Array.prototype.lastIndex = function() {
return this.length - 1;
}
console.log(array[array.lastIndex()]);
Run Code Online (Sandbox Code Playgroud)
VS
console.log(array[array.length - 1]);
Run Code Online (Sandbox Code Playgroud)
从技术上讲,后一种方法使用少一个字符,但也使用幻数.当然,在这种情况下,可读性可能不会受到影响,但魔术数字很糟糕.使用哪种更好的做法?