I have a set of buttons, which when clicked trigger a function which toggles their ID to an array called MyArray
function AddToArray(a, v) {
var v = this.id
var a = myArray
var i = a.indexOf(v);
if (i === -1)
a.push(v);
else
a.splice(i,1);
}
I want to use this same function for a different set of buttons. Instead of toggling their IDs to MyArray, I wish to toggle them to MySecondArray
At the moment, I simple have two separate functions, but it seems wrong to repeat code.
I considered adding a data-attribute to the buttons with a value of MyArray or MySecondArray and then turning this string into a variable to push to the relevant array. I understand though that using functions such as eval() can be insecure.
Therefore, I am wondering what the best way to do this is, in terms of reusing functions in general?
myArraya parameter of the function and pass in the value you want? Though this function is already pretty strange in that the first thing it does is shadow any values that were passed to it.var a = myArraydoes not make sense when you have a in the function declaration. Instead remove the line and a IS myArry OR MySecondArray if you pass it as first parameter