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?
function toggleToArray(arr, id) {
const i = arr.indexOf(id);
return i === -1 ? [...arr, id] : arr.filter(val => val !== id);
}
// add if id does not exist
const myArr = toggleToArray(['a', 'b', 'c'], 'd');
console.log('toggltoarray.js: 8 myArr ', myArr);
// remove if exists
const myArr1 = toggleToArray(myArr, 'd');
console.log('toggltoarray.js: 12 myArr1 ', myArr1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.