2013-10-23 95 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(); 
}