DaveR
DaveR

Reputation: 2483

How to use a function parameter to refer to the variable of the same name?

I'm making a jquery plugin to show piano scales.

I have a function called markScale(a, b) which will be used to highlight certain scales (the a parameter gives the pitch of the starting note, ie. how many semitones up from C, the default scale). That's no problem.

The problem comes with b, the type of scale or chord to display. I have defined which keys to use in the different types of scale as follows:

  var majorScale=[12,14,16,17,19,21,23,24];
  var nminorScale=[12,14,15,17,19,20,22,24];
  var hminorScale=[12,14,15,17,19,20,23,24];

And so what I'm looking to do is the following:

  for(i=0;i<8;i++){
  $('#key-'+(b[i]+a)+'-marker').show();
   }

markScale(0,"majorScale") doesn't work, because that's just a string and doesn't refer to the array variable that I need.

How do I refer to the array variable as a parameter of the function?

Thanks

Upvotes: 0

Views: 70

Answers (2)

mweppler
mweppler

Reputation: 25

Its hard to tell without more context, but have you tried passing the array majorScale itself to the markScale() function?

as in: markScale(c, majorScale);

instead of a string: markScale(c, "majorScale");

Upvotes: 0

user1106925
user1106925

Reputation:

I think we're missing a little info, but if you want to asccess the scale by name, put the arrays in an object instead of individual variables.

var scales = {
    majorScale:[12,14,16,17,19,21,23,24],
    nminorScale:[12,14,15,17,19,20,22,24],
    hminorScale:[12,14,15,17,19,20,23,24]
};

Then you can reference the scales using a string...

var the_scale = "majorScale"

scales[the_scale][i];

While it is possible to refer to local variables from a string, it requires an approach that is generally not recommended. Global variables are a little easier.


If you were trying to pass the scale, then you don't use a string at all. You just use a direct reference. majorScale

Upvotes: 2

Related Questions