0

I'm trying to change function name by adding an increment number to it's end each time it gets executed, to achieve a new function name each time the code is executed.

<button id="Btn">alert text</button>

function text1(){
    alert("This is text1");
}

function text2(){
    alert("This is text2");
}

function text3(){
    alert("This is text3");
}

var Btn = document.getElementById("Btn");
var i = 1;

Btn.addEventListener("click", function alertText(){

i++;

//bellow line in the first time should be text2()

text+i();

}

  • 1
    This looks like an X/Y problem - you COULD do `window["text"+i]()` but I would strongly recommend `const texts = ["Text 1","Text2","Text 3"]; alert(texts[i])` – mplungjan Apr 21 '22 at 12:57
  • use array of functions for such need – Alexei Petrenko Apr 21 '22 at 12:58
  • Use an array of functions, not a bunch of globals named numerically. Better yet, since the functions are identical except for a string literal in each: put the strings in the array and pass them to the function as an argument. – Quentin Apr 21 '22 at 12:58
  • 2
    The actual problem you're trying to solve is to run different code each time the button is clicked. There are various ways to do this as you can see from the comments; creating a bunch of numbered but otherwise almost identical functions is the worst possible way. –  Apr 21 '22 at 13:01
  • Here's one way to solve this: https://jsfiddle.net/g9dcf2a3/ –  Apr 21 '22 at 13:05
  • Here is another https://jsfiddle.net/mplungjan/f378gu92/ – mplungjan Apr 21 '22 at 13:13
  • Thanks a lot @Chris G and all of you guys for the help and the useful information – Ahmed Malik Apr 21 '22 at 14:05

0 Answers0