Posted on May 24th, 2009 at 15:50 by fr3@K
上週在我的 feed reader 上看到了個好玩的東西 - Konami Code.
原文作者引用了 jQuery 主站上的一段 JavaScript, 也明白的說了這個 script 的一個缺陷 - 隨著愈多的 keypress, 它會愈跑愈慢:
It’s a bit sloppy, though: the kkeys array will increase in size with every keypress, which means the page will get slower and slower as you press keys.
把 coding style 調整成自己比較習慣的風格, 加上幾行處理過多 user key log 的 code 以修正原文作者所說的問題, 補上了注解. Here it is, 我的第一個 JavaScript 程式:
-
if(window.addEventListener)
-
{
-
var target = "http://fsfoundry.org/codefreak/2009/05/24/my-first-javascript-konami-code/";
-
var konami_code = "38,38,40,40,37,39,37,39,66,65";
-
var user_key_log = [];
-
var max_keys_to_log = 10;
-
-
window.addEventListener(
-
"keydown",
-
function(ev)
-
{
-
user_key_log.push(ev.keyCode); // push_back
-
var user_keys = user_key_log.toString();
-
-
// Searches for konami_code in user_keys.
-
if(user_keys.indexOf(konami_code)>= 0)
-
window.location = target;
-
-
// Cleans up user_key_log, if its length out
-
// numbered max_keys_to_log.
-
while(user_key_log.length> max_keys_to_log)
-
user_key_log.shift(); // pop_front
-
},
-
true);
-
}
只要你沒把 browser 的 JavaScript 關掉, 在 COdE fr3@K 的任何一頁輸入 上上下下左右左右BA, 就會把你帶回到這篇文字.
Tested to work with:
- Firefox 3.0.10
- Opera 9.64
- Epiphany Web Browser 2.24.1
Note: I don't know why, but as the original script from jQuery, my version doesn't work with IE 6 on my XP box at office.
Something interesting that I can't help wondering, 連我這個從沒認真看過 JavaScript 更別說寫過的人都能在知道問題後稍微 google 一下把這問題修掉, 難道 jQuery 網站的作者是覺得這段 code 純屬搞笑而隨便寫寫嗎?
![]() |
|
| Previous Post « I Like to Move It « |
Next Post » Observer Pattern, Done Differently » |








因為 IE 要用 window.attachEvent 而不是 addEventListener :p
Comment by ericsk — May 24, 2009 @ 17:29