以下是我迄今为止的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”,如果是这样,则获取倒数第三个项目。
编辑:
最近,我又提出了一个解决方案,我现在认为这是最适合我的需求的:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
根据上述定义,我现在可以说:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
名称“w”代表“包装器”。您可以看到如何轻松添加更多除了“last()”之外的方法。
我说“最符合我的需要”,因为这允许我可以很容易地添加其他这样的“助手方法”任何JavaScript内置类型。发生了什么记住Lisp的car()和cdr()例子
编辑:
最近,我又提出了一个解决方案,我现在认为这是最适合我的需求的:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
根据上述定义,我现在可以说:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
名称“w”代表“包装器”。您可以看到如何轻松添加更多除了“last()”之外的方法。
我说“最符合我的需要”,因为这允许我可以很容易地添加其他这样的“助手方法”任何JavaScript内置类型。发生了什么记住Lisp的car()和cdr()例子
以下内容如何:
if ('index.html' === array[array.length - 1]) {
//do this
} else {
//do that
}
如果使用Undercore或Lodash,则可以使用_.last(),例如:
if ('index.html' === _.last(array)) {
//do this
} else {
//do that
}
或者您可以创建自己的最后一个函数:
const _last = arr => arr[arr.length - 1];
并像这样使用:
if ('index.html' === _last(array)) {
//do this
} else {
//do that
}