0

How do I call a function through an element of an array? I want to shorten my code so that I can use 1 function in multiple places, but my method is not good.

var a = 1;
var b = 1;

var arRay = [];
arRay.length = 5;

arRay[0] = function functIon(){
  if(a >= b){
  a = a + b;
  document.getElementById('demo').innerHTML = a;
  }
};

function test(){
  arRay[0];
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<button onclick="test()">Click me, please!</button>
<p>a + b = <span id="demo">?</span></p>
</body>
</html>

Even though ctrl + c, ctrl + v, even when used in too many places is the same part.

Expo
  • 3
  • 4

1 Answers1

1

You need to actually invoke the array element (arRay[0]()):

var a = 1;
var b = 1;

var arRay = [];
arRay.length = 5;

arRay[0] = function functIon(){
  if(a >= b){
  a = a + b;
  document.getElementById('demo').innerHTML = a;
  }
};

function test(){
  arRay[0]();
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<button onclick="test()">Click me, please!</button>
<p>a + b = <span id="demo">?</span></p>
</body>
</html>
gabriel.hayes
  • 2,267
  • 12
  • 15