// Bind an event handler to keydown on the entire document
document.addEventListener("keydown",function(e){
// Everything in here happens on keydown
// keys must be an array declared somewhere earlier in the code
// This loops through that array
for(i=0;i < keys.length; i++) {
// If the current key we are looking at in the array
// is the key that was pressed
if(e.keyCode == keys[i]){
// Get the (i+1)th childnode of foo
var tri = document.getElementById("foo").childNodes[i];
// If i = 0 get the second element (not the first)
if(i==0){
var tri = document.getElementById("foo").childNodes[1];
}
// If i == 1 get the fourth element (not the second)
if(i==1){
var tri = document.getElementById("foo").childNodes[3];
}
// Otherwise get the (i*2+2)th element.
if(i > 1) {
var tri = document.getElementById("foo").childNodes[(i*2)+1];
}
// Here we are still in an if-statement, in a loop, in a function,
// so there is probably more code here, at least some closing }'s
注意var tri = document.getElementById("foo").childNodes[i];
是一個無用的線,因爲i
不能爲負,接下來的三個之一,如果語句總是會成功,tri
將被覆蓋。
還要注意的是,當i = 0
,(i*2)+1 = 1
當i = 1
,(i*2)+1 = 3
,所以與其他兩個if語句是無用的,以及因爲第三覆蓋了所有的情況下,並不需要甚至是如果子句。上面的代碼是100%等同於:
document.addEventListener("keydown",function(e){
for(i=0;i < keys.length; i++) {
if(e.keyCode == keys[i]){
var tri = document.getElementById("foo").childNodes[(i*2)+1];
...
i
由於是稱爲keys
用於通過數組迭代變量,和所選擇的節點取決於i
。 keys
必須是一個具有不尋常目的的數組。它是一個keyCodes數組,其中keyCode在數組中的位置確定在按下該鍵時應該選擇並存儲在tri
中的哪個節點。
將導致丟失關閉大括號的語法錯誤 – Ibu
@Ibu - 顯然這個片段不包含整個方法 –