当我正在执行某项功能时,我的变量出现了问题。这只是一个愚蠢的例子。在我的代码中,我有很多我想要在函数中使用的变量,所以我不必为每个变量“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>
答案 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 :(得分:1)
另外,关于ifs,更优雅的方法是让对象包含所有动作,如下所示:
var actions = {
frog:function(){
//action a
},
pig:function(){
//action b
}
}
然后只需找到对象中的动作并在找到时调用它
var action = actions['ex' + x]
if (action) {
action();
}