1

I have a number of arrays that contain multiple values.

 var ab = [".inb", ".bhm", ".bab", ".mdr"];
 var bc = [".thc", ".lsl", ".cma", ".vth"];
 var de = [".myh", ".rte", ".bab", ".tzs"];
    etc

I am using a select to specify which array to iterate through changing css values on a menu

 $('#browse2').on('change', function () {

    // the value of #browse2 would be ab or bc or de etc
    var fv = $('#browse2').val();

    for (i = 0; i < fv.length; ++i) {
       $(fv[i]).css('opacity', '1.0');
    }

 });

But unfortunately this code only goes through the fv value itself (ie: ab), it doesn't call the array with the same variable name. How do I tell the for statement to use the variable with the same name as the fv value?

2
  • $(fv[i]).css('opacity', fv); ???? Commented Nov 4, 2015 at 11:46
  • 1
    Either you will have to use if conditions to decide which array to use, or you can add all arrays in a object and try object[arrayName]. Commented Nov 4, 2015 at 11:49

2 Answers 2

2

I would advice you to store arrays as properties of an object. You will be able to access them with the help of bracket notation:

var obj = {
     ab: [".inb", ".bhm", ".bab", ".mdr"],
     bc: [".thc", ".lsl", ".cma", ".vth"],
     de: [".myh", ".rte", ".bab", ".tzs"]    
 }; 

 $('#browse2').on('change', function () {   
    var fv = $('#browse2').val();

    for (i = 0; i < obj[fv].length; ++i) {
       $(obj[fv][i]).css('opacity', '1.0');
    }

 });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks to both Lazarev and Mark. With Mark's correction, this works nicely.
Sorry, I've missed it. Glad, to help you!
0

Change this line:

var fv = $('#browse2').val();

To:

var fvValue = $('#browse2').val();
var fv;
switch(fvValue){
   case "ab": fv = ab; break;
   case "bc": fv = bc; break;
   case "cd": fv = cd; break;
}

Basically in fv you were storing a string of "ab" rather than a reference to the ab array object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.