2

I was tasked by my professor to make a simple Javascript program that displays simple math problems and their answers in a two dimensional table using a random number. Previously he gave us the example of using a function to write into a table like this:

function RandomGen() {
Random = math.floor(Math.random()*60);
    document.writeln("<th>");
       document.writeln(Random);
       document.writeln("</th>");
}
RandomGen();

In order to use an array, can I do this?

var RandomArray [

RandomGen(),
second_function(),
third_function(),
forth_function(),
]

RandomArray[0];

How do I append the functions together to write into a table?

Jon Adams
  • 24,464
  • 18
  • 82
  • 120
andrsnn
  • 1,591
  • 5
  • 25
  • 43

2 Answers2

3

You almost got it. The correct syntax is:

var randomArray = [    
  RandomGen,
  second_function,
  third_function,
  forth_function
];

randomArray[0](); // this calls RandomGen
randomArray[1](); // this calls second_function

Remember the basic syntax rules:

  1. A function name with no paranthesis is a function reference. It behaves just like any reference and so can be treated as a variable. Which means you can assign it to another variable, pass it into another function and as the example above stuff it into an array.

  2. Adding paranthesis () to a function reference causes the function to be called. It doesn't matter if the function reference is a plain old function name or stored in another variable or stored in an array.

plalx
  • 42,889
  • 6
  • 74
  • 90
slebetman
  • 109,858
  • 19
  • 140
  • 171
1

You can store the function in a variable, then put the variables in an array, and then access them from the array to call them.

var add = function(x,y){ return x + y; };
var multiply = function(x,y){ return x * y; };
var maths = [];
maths.push(add);
maths.push(multiply);
maths[0](1,2);//3
maths[1](3,4);//12

Conversely, you could do this with an object.

var maths = {};
maths.add = function(x,y){ return x + y; };
var four = maths.add(1,3);

Obviously you will have to modify these to match your exact situation.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • gotcha, how would i then write into a table? – andrsnn Mar 26 '13 at 06:04
  • I keep pressing enter sorrylol document.writeln("") maths[0](1,2); document.writeln("")? – andrsnn Mar 26 '13 at 06:05
  • @user2210274 - If you wanted `maths` content in the `document.write` it would be `document.writeln(""+maths[0](1,3)+"");` where the `+` sigh concatenates the strings together. That would result in writing `4` to the page. – Travis J Mar 26 '13 at 06:07
  • do you know how you would then print an element inthe array to the DOM into a html element using getelementbyid? – andrsnn Mar 26 '13 at 16:05
  • @user2210274 - You would use the `document.createElement` and `.appendChild` methods. Here is a simple example: http://stackoverflow.com/a/15580994/1026459 – Travis J Mar 26 '13 at 16:26