次のような発言があります。
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)$/)) {
// ...
}
...しかし、ケンのコメントによると、効率が低下します。
新しいブラウザーに使用し、ここで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' )