我有这样的声明:
if(window.location.hash != '' && window.location.hash != '#all' && window.location.hash != '#')
我可以写它,所以我只需要提到window.location.hash
一次吗?
我有这样的声明:
if(window.location.hash != '' && window.location.hash != '#all' && window.location.hash != '#')
我可以写它,所以我只需要提到window.location.hash
一次吗?
显而易见的方法是:
var h = window.location.hash;
if (h != '' && h != '#all' && h != '#')
您可以使用 in 运算符和对象文字:
if (!(window.location.hash in {'':0, '#all':0, '#':0}))
这通过测试对象的键来工作(0 只是填充符)。
另请注意,如果您弄乱了object
的原型,这可能会中断
正则表达式?不那么可读,但足够简洁:
if (/^(|#|#all)$/.test(window.location.hash)) {
// ...
}
这也有效:
if (window.location.hash.match(/^(|#|#all)$/)) {
// ...
}
...但根据 Ken 的评论,它的效率较低。
用于indexOf
较新的浏览器,并为较旧的浏览器提供实现,您可以在此处找到。
// return value of -1 indicates hash wasn't found
["", "#all", "#"].indexOf(window.location.hash)
只是一个补充,因为除了相当多的不重复自己的方法外,没有人提到:
在浏览器中,
window
是对象,所以如果您没有在当前范围内Global
命名的另一个属性(不太可能),请将其切断 。足够"location"
location.hash
我认为最好检查长度,因为第一个字符始终是哈希。
var h = location.hash;
if ( h.length > 1 && h != '#top' )