检查[variable name] + [number]是否存在



我使用下面的代码检查var1是否存在,然后分配另一个变量(提示)来存储var1,前提是用户在变量中输入。问题是我有大约20个变量需要检查,所以我的代码看起来像下面的10倍:

    if (typeof var1 !== 'undefined') {
        if(selection==var1){
            var promt = var1;
        }           
    }
    if (typeof var2 !== 'undefined') {
        if(selection==var2){
            var promt = var2;
        }           
    }

这(a)产生了大量低效的代码,(b)如果我有超过20个变量,可能会导致错误。
是否有方法检查var1, var2, var3等。存在然后停止检查当变量停止?
我们的目标是能够有一百个变量,并且仍然有相同数量的代码,如果有两个。

如果您的变量是对象上的字段,您可以轻松地动态构建字段名:

fieldname = 'var' + index;
if (typeof obj[fieldname] !== 'undefined') {
    if (selection == obj[fieldname]){
        var promt = obj[fieldname];
    }           
}

对于局部变量,我不能提供一个解决方案。

首先var保留字在javascript中,所以你不能使用它作为变量名,因此我在这里使用_var代替。

我为这个解决方案做了一个jsFiddle,所以请检查一下。

你也可以看看下面的代码:

for (i in _var) {
  // Loop through all values in var
  if ((typeof _var [i] !== undefined) &&
    selection_array.indexOf(_var [i]) >= 0) {
    // note that array.indexOf returns -1 if selection_array does not contain var [i]
        prompt = _var[i]; // use this if you only want last var[i] satisifying the condition to be stored
    prompt_array.push(_var[i]);// use this if you want to store all satisifying values of var[i]
  }
}

也检查下面的代码片段

// Lets declare and give some example value to _var, Note that you cannot use var as variable name as it is a reserver word in javascript
var _var = ['foo1', 'foo2', 'foo3', 'foo4'];
// Declare a variable called prompt (actually not necessary normally)
var prompt;
// Declare a array called prompt_array to store the output
var prompt_array = [];
// Declare and give some example value to selection_array
var selection_array = ['foo2', 'foo3'];
// main program to solve the problem
for (i in _var) {
  // Loop through all values in var
  if ((typeof _var [i] !== undefined) &&
    selection_array.indexOf(_var [i]) >= 0) {
    // note that array.indexOf returns -1 if selection_array does not contain var [i]
		prompt = _var[i]; // use this if you only want last var[i] satisifying the condition to be stored
    prompt_array.push(_var[i]);// use this if you want to store all satisifying values of var[i]
  }
}
// output for visualizing the result
document.getElementById('output').innerHTML += 'prompt = ' + prompt + '<br/>';
document.getElementById('output').innerHTML += 'prompt_array = ' + prompt_array.toString();
<div id="output">
</div>

d

最新更新