1

I am trying to create a function that is called by multiple different buttons, and that selects a specific array depending on which button called the function.

For example:

If a button with id="Anterior" called the function, the function selects array named plusAnterior:

var plusAnterior = ["p", "b", "t", "d", "ɸ", "β", "f", "v", "θ", "ð", "s", "z", "m", "n", "l", "ɬ", "r", "ɾ"];
var minusAnterior = ["c", "ɟ", "k", "g", "ʃ", "ʒ", "x", "ɣ", "ɲ", "ŋ", "j", "w", "ʡ", "h"];
var toAdd = [];

function addFeature(featureId) {
  if (activeFeatures === 0) {
    toAdd = // plusAnterior called here
  }
}

The problem is, I cannot simply do toAdd = plusAnterior because I want my function to work for any button pressed. I thought of doing something like getElementById("plus" + featureId), but I can't since the arrays I'm trying to select are not in my HTML.

Thank you for any help.

3
  • @EmilieHass why would you call getElementById to retrieve a javascript data structure? getElementById are stricly for DOM elements. Commented Dec 17, 2018 at 15:48
  • @andreihondrari i think, he said the same thing in last sentence. Commented Dec 17, 2018 at 15:50
  • @ahmet_y yes I know, but I still don't understand why would he do that. Commented Dec 17, 2018 at 15:51

1 Answer 1

3

In javascript, you can use an object almost as a key/value array.

var testObject = {
  featureId_a: [1, 2, 3, 4, 5], // etc
  featureId_b: [1, 2, 3, 4, 5] // etc
}

Then we can return it with your method like so...

function addFeature(featureId) {
  return testObject[featureId];
}

I think this is what you mean. Otherwise, you could use a 2D array and select based on the index. But it depends on your data really the best option.

For brevity and some sanitization, you should, of course, check the object for the property.

if(testObject.hasOwnProperty(featureId)){
  return testObject[featureId];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is what I was searching for! Thank you very much!

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.