【发布时间】:2011-05-10 15:18:36
【问题描述】:
我有这样的声明:
if(window.location.hash != '' && window.location.hash != '#all' && window.location.hash != '#')
我可以这样写,所以我只需要提到一次window.location.hash吗?
【问题讨论】:
标签: javascript syntactic-sugar
我有这样的声明:
if(window.location.hash != '' && window.location.hash != '#all' && window.location.hash != '#')
我可以这样写,所以我只需要提到一次window.location.hash吗?
【问题讨论】:
标签: javascript syntactic-sugar
这样做的明显方法是:
var h = window.location.hash;
if (h != '' && h != '#all' && h != '#')
【讨论】:
你可以使用 in 操作符和一个对象字面量:
if (!(window.location.hash in {'':0, '#all':0, '#':0}))
这通过测试对象的键来工作(0 只是填充)。
另请注意,如果您弄乱object 的原型,这可能会中断
【讨论】:
indexOf,所以我想这样更好
!吗? 0 没有做到这一点吗?快速的search 建议在简单的“或”情况下使用1,所以我猜0 会否定它?
in 只是检查键。
1 s,无论哪种情况?
正则表达式?不那么可读,但足够简洁:
if (/^(|#|#all)$/.test(window.location.hash)) {
// ...
}
这也有效:
if (window.location.hash.match(/^(|#|#all)$/)) {
// ...
}
...但根据 Ken 的评论,它的效率较低。
【讨论】:
search 而不是match,并且都应该测试值== -1。 String 的search 方法与RegExp 的test 方法相当,而它的match 方法与RegExp 的exec 方法相当。 match 和 exec 速度较慢,但提供更多信息(或 null 不匹配),而 search 和 test 只需给出第一个匹配开始的字符串中的索引(或 -1 不匹配)匹配)。
RegExp.test 返回一个布尔值,而不是一个索引。不过,我同意你其余的评论。我的第二个示例效率略低,但比您提出的替代方案更具可读性 - 我猜,问题的重点是简洁。
为较新的浏览器使用indexOf,并为较旧的浏览器提供一个实现,您可以找到here。
// 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' )
【讨论】: