我有这样的语句:有没有更快的方法来编写条件语句?
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 != '#')
您可以使用运营商和对象文本:
if (!(window.location.hash in {'':0, '#all':0, '#':0}))
这部作品通过测试对象的键(0的只是填料)。
还要注意的是,如果你是object
的原型
使用数组将是整洁(不需要填充0)解决方案,但是IE没有'indexOf',所以我想这是更好的 – 2010-11-16 05:42:29
你真正需要的'!'? '0'是不是完成了?快速[搜索](http://snippets.dzone.com/posts/show/6557)建议在简单的“或”情况下使用'1',所以我猜“0”会否定它? – 2010-11-16 05:51:57
@Isaac 0的意义不大,'in'只是检查键。 – cobbal 2010-11-16 05:54:37
正则表达式?事实并非如此可读,但足以简洁:
if (/^(|#|#all)$/.test(window.location.hash)) {
// ...
}
这也适用于:
if (window.location.hash.match(/^(|#|#all)$/)) {
// ...
}
...但它的效率较低,每Ken的评论。
为了完全准确,第二个示例应该使用'search'而不是'match',并且都应该测试值== -1。字符串的“搜索”方法与RegExp的“test”方法相当,而其“匹配”方法与RegExp的“exec”方法相当。 'match'和'exec'比较慢,但提供更多信息(或者不匹配时为null),而search和test只是给出第一个匹配开始的字符串的索引比赛)。 – 2010-11-16 06:11:00
'RegExp.test'返回一个布尔值,而不是索引。不过,我同意你的评论的其余部分。我的第二个例子效率稍低,但比您提出的替代方案更具可读性 - 我猜,简洁是问题的关键。 – harto 2010-11-16 23:35:52
对较新的浏览器使用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')
+1。很好很简单 – cobbal 2010-11-16 05:44:27
我倾向于使用局部变量这种方式很多。它也使调试更容易。 – 2010-11-16 21:26:49