1

我有这样的声明:

 if(window.location.hash != '' && window.location.hash != '#all' && window.location.hash != '#')

我可以写它,所以我只需要提到window.location.hash一次吗?

4

6 回答 6

7

显而易见的方法是:

var h = window.location.hash;
if (h != '' && h != '#all' && h != '#')
于 2010-11-16T05:42:10.387 回答
6

您可以使用 in 运算符和对象文字:

if (!(window.location.hash in {'':0, '#all':0, '#':0}))

这通过测试对象的键来工作(0 只是填充符)。

另请注意,如果您弄乱了object的原型,这可能会中断

于 2010-11-16T05:26:33.050 回答
3

正则表达式?不那么可读,但足够简洁:

if (/^(|#|#all)$/.test(window.location.hash)) {
    // ...
}

这也有效:

if (window.location.hash.match(/^(|#|#all)$/)) {
    // ...
}

...但根据 Ken 的评论,它的效率较低。

于 2010-11-16T05:49:45.427 回答
1

用于indexOf较新的浏览器,并为较旧的浏览器提供实现,您可以在此处找到。

// return value of -1 indicates hash wasn't found
["", "#all", "#"].indexOf(window.location.hash)
于 2010-11-16T05:55:02.587 回答
1

只是一个补充,因为除了相当多的不重复自己的方法外,没有人提到:

在浏览器中,window是对象,所以如果您没有在当前范围内Global 命名的另一个属性(不太可能),请将其切断 。足够"location"location.hash

于 2010-11-16T06:54:31.253 回答
1

我认为最好检查长度,因为第一个字符始终是哈希。

var h = location.hash;
if ( h.length > 1 && h != '#top' )
于 2010-11-16T08:02:22.887 回答