Is it possible to get the index of the array object that called a function?

So I learned some time ago on this forum that the same function can be called by a button press and it’s possible to determine which button did the pressing:

function buttonPressListener(){
    switch (this) {
        case button1:
            doTask1();
            break;
        case button2:
            doTask2();
            break;
    }
}

Now I want to know if it’s possible to get the array index of the button (assuming it was an array of buttons) that called the function.

button[0].mouseClicked(buttonPressListener);
button[1].mouseClicked(buttonPressListener);
function buttonPressListener(){
    //code that determines what the index 
    //of the button that called this function
}
1 Like

const idx = buttons.indexOf(this), btn = buttons[idx];

3 Likes

You could modify your buttonPressListener function to take a parameter, and then pass that parameter into the function using an anonymous callback function. Something like this:

button[0].mouseClicked(() => { buttonPressListener(0); });
button[1].mouseClicked(() => { buttonPressListener(1); });
4 Likes