2013-10-23 39 views
1

當我正在執行一個函數時,我的變量有問題。這只是一個愚蠢的例子。在我的代碼中,我有很多變量要在函數中使用,所以我不必爲每個變量「ex1,ex2等等」重複編寫函數。「下面是我想要做的真的很簡單。首先檢查「ex1」它等於聲明的值,然後執行操作(實際代碼中的動畫)。然後對「ex2」執行相同的操作。有沒有簡單的方法來做到這一點?在函數內聲明的變量 - 循環

<script> 
var ex1 = 'frog'; //Those are not set manually. ID's in real code 
var ex2 = 'pig'; 
var ex3 = 'horse'; 
var ex4 = 'bird'; 

var x = 0; 
setInterval("call", 5000); 
function call(){ 

    x++; 

    if(('ex' + x) == 'frog'){ 
    //action a 
    } 
    else if(('ex' + x) == 'pig'){ 
    //action b 
    } 
    else if(('ex' + x) == 'horse'){ 
    //action c 
    } 
    else if(('ex' + x) == 'bird'){ 
    //action d 
    } 

} 

</script> 
+1

'窗口[ 'EX' + X]'。應該有一個副本。 – Zeta

+0

like if(window ['ex'+ x] == y)? @Zeta – PeterP

+0

我認爲讓數組變得更容易。 –

回答

2

全局變量是window對象的屬性(在瀏覽器反正)。您可以訪問使用方括號的屬性是這樣的:

var ex1 = 'frog'; //Those are not set manually. ID's in real code 
var ex2 = 'pig'; 
var ex3 = 'horse'; 
var ex4 = 'bird'; 

var x = 0; 

function call(){ 

    x++; 

    if(window['ex' + x] === 'frog'){ 
    //action a 
    } 
    else if(window['ex' + x] === 'pig'){ 
    //action b 
    } 
    else if(window['ex' + x] === 'horse'){ 
    //action c 
    } 
    else if(window['ex' + x] === 'bird'){ 
    //action d 
    } 

} 

setInterval(call, 5000); 

然而,使ex陣列可能會更好這裏:

var ex = []; 
ex[1] = 'frog'; //Those are not set manually. ID's in real code 
ex[2] = 'pig'; 
ex[3] = 'horse'; 
ex[4] = 'bird'; 

var x = 0; 

function call(){ 

    x++; 

    if(ex[x] === 'frog'){ 
    //action a 
    } 
    else if(ex[x] === 'pig'){ 
    //action b 
    } 
    else if(ex[x] === 'horse'){ 
    //action c 
    } 
    else if(ex[x] === 'bird'){ 
    //action d 
    } 

} 

setInterval(call, 5000); 

如果你這樣做了很多串,使用一個switch聲明:

var ex = []; 
ex[1] = 'frog'; //Those are not set manually. ID's in real code 
ex[2] = 'pig'; 
ex[3] = 'horse'; 
ex[4] = 'bird'; 

var x = 0; 

function call(){ 

    x++; 
    switch(ex[x]) { 
     case 'frog': 
      //action a 
      break; 
     case 'pig': 
      //action b 
      break; 
     case 'horse': 
      //action c 
      break; 
     case 'bird': 
      //action d 
      break; 
    } 

} 

setInterval(call, 5000); 
1

另外,關於IFS,更優雅的辦法是有一個包含所有操作的對象,這樣的:

var actions = { 
    frog:function(){ 
    //action a 
    }, 
    pig:function(){ 
    //action b 
    } 
} 

,然後就找到對象的行動,並呼籲,如果發現

var action = actions['ex' + x] 
if (action) { 
    action(); 
}