开发者

Is there a quicker way to write conditional statements?

开发者 https://www.devze.com 2023-01-25 01:49 出处:网络
I have a statement like this: if(window.location.hash != \'\' && window.location.hash != \'#all\' &&开发者_运维百科amp; window.location.hash != \'#\')

I have a statement like this:

 if(window.location.hash != '' && window.location.hash != '#all' &&开发者_运维百科amp; window.location.hash != '#')

Can I write it so I only have to mention window.location.hash once?


the obvious way to do this is:

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


you can use the in operator and an object literal:

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

this works by testing the keys of the object (the 0's are just filler).

Also note that this may break if you are messing with object's prototype


Regular expression? Not so readable, but concise enough:

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

This also works:

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

... but it's less efficient, per Ken's comment.


Use indexOf for newer browsers, and supply an implementation for older browsers which you can find here.

// return value of -1 indicates hash wasn't found
["", "#all", "#"].indexOf(window.location.hash)


Just an addition, because besides quite good variety of do not repeat yourself approaches, nobody mentioned that:

In browsers, window is Global object, so cut it off, if you dont have another property named "location" in the current scope (unlikely). location.hash is enough


I think it is good to check on length since the first character always is an hash.

var h = location.hash;
if ( h.length > 1 && h != '#top' )
0

精彩评论

暂无评论...
验证码 换一张
取 消