Change var in loop

时间:2016-10-20 19:02:58

标签: javascript jquery

I have a loop

var names = ['apple', 'pear', 'something']
var age = ['12','344','132']

(i have 20 vars like this)

for (var i = 0; i < names.length; i++) {
    Something(names[i]);
}

i get the type of something with an jquery var name = $('[name=id]').val();

is it possible to do an if else so if the var name is equal to any of the variables like here above then the names.length will change into that.

Example if the outcome of the var name = $('[name=id]').val(); is age then the loop will change into

for (var i = 0; i < age.length; i++) {
    Something(age[i]);
}

3 个答案:

答案 0 :(得分:4)

Yes, if you store those variables into an object.

var container = {};
container.names = ['apple', 'pear', 'something'];
container.age = ['12','344','132'];

var name = $('[name=id]').val();

for (var i = 0; i < container[name].length; i++) {
    Something(container[name][i]);
}

[edit]
You can also check that what's stored in name corresponds to a valid array inside your container by calling Array.isArray(container[name]).

答案 1 :(得分:1)

You can achieve this in a quite different way.

Define all you variables in an object like below.

var data = {
    names: ['apple', 'pear', 'something'],
    age: ['12','344','132'],
    //...
}

here you get the type

var name = $('[name=id]').val();

Now do the loop like below, which should be as expected,

for (var i = 0; i < data[name].length; i++) {
    Something(data[name][i]);
}

答案 2 :(得分:1)

What you are saying might be possible depending on the scope of your variables. For example, if they are set globally on window, then you could potentially use Something(window[name][i]);, however I wouldn't recommend doing this. Instead I would set up your code with an object instead of variables, like this:

var data = {
  names: ['apple', 'pear', 'something'],
  age: ['12', '344', '132']
};

Then you can simply do what you describe:

var name = $('[name=id]').val();
for (var i = 0; i < data[name].length; i++) {
  Something(data[name][i]);
}

Another way you could do this is by creating a function and passing in the appropriate variable:

var names = ['apple', 'pear', 'something']
var age = ['12','344','132']

function processItems(items) {
  for (var i = 0; i < items.length; i++) {
    Something(items[i]);
  }
}

switch ($('[name=id]').val()) {
  case 'name':
    processItems(name);
    break;
  case 'age':
    processItems(age);
    break;
}