user6644024
user6644024

Reputation:

How call function using variable in js?

for example, I have code like this:

var test = function() {
   return Math.random();
}

var randomNumber = test();


// I want to call test() via the randomNumber variable, 
// use this variable on another function or etc...
// for example here
for (var i = 0; i < 5; i++) {
   console.log(randomNumber); // and it should be show 4 random numbers
}

Is this possible?
Thanks to advance.

Upvotes: 0

Views: 33

Answers (2)

blurfus
blurfus

Reputation: 14031

You could assign the value returned by the function to the variable inside the loop and then display it.

Kinda like the code below

// define function
var test = function() {
  return Math.random();
}

// define variable
var randomNumber;

// loop
for (var i = 0; i < 5; i++) {
  // invoke function, assign value to variable
  randomNumber = test();

  // output it to console.
  console.log(randomNumber);
}

UPDATE

If you do not want to write code to 'loop' thru your array, you can use a fake array and map the same function to it.

You are not looping thru it yourself but looping thru the array is being performed nonetheless.

// array of fake values
var iterations = [0, 1, 2, 3, 4];

// returns an array of random numbers
console.log(iterations.map(function(elem) {
  return Math.random();
}));

Upvotes: 0

Paul
Paul

Reputation: 141829

I believe you want to assign the function reference to randomNumber instead of calling the function and assigning its return value.

var test = function() {
   return Math.random();
}

// Assign test to randomNumber, but don't call it here
var randomNumber = test;

for (var i = 0; i < 5; i++) {
   console.log(randomNumber()); // call it here
}

Upvotes: 2

Related Questions