0

I would like to generate an array and store the value inside a variable and export that variable in a way that i can acess it anywhere i want in my application.

const generateNewArray = () => {

  var numberOfArrayItems = 40;
  var currentArray = Array.from({ length: numberOfArrayItems }, () => Math.floor(Math.random() * 200) + 1);

  return currentArray;
}


export { generateNewArray }

But, until right now i could only export the function. And when i invoke "generateNewArray" i get the function body as answer, and when i invoke "generateNewArray()" i get another random array, different from the original.

How can i acess the "currentArray" variable from anywhere in my application?

Thanks!

2
  • the value returned from this function will be different everytime you call it because you geta random number so it's normal no ? Commented Jun 27, 2021 at 22:58
  • Yep! Thats correct, i want to generate a random array in every function invoke but i would like to store the value in a variable that i can acess anywhere i want. And if i invoke that function, the value of the variable will change. Commented Jun 28, 2021 at 7:55

1 Answer 1

1

You need to create a local variable, set its value, and then export the variable itself:

const generateNewArray = () => {

  var numberOfArrayItems = 40;
  var currentArray = Array.from({ length: numberOfArrayItems }, 
    () => Math.floor(Math.random() * 200) + 1);
  
  return currentArray;
}

const myRandomArray = generateNewArray();
export { myRandomArray }
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Christian, thanks for the answer! But i would like that the variable is the same anywhere in the application, but when i invoke the function the value of the variable changes. So: myRandomArray is gonna generate a array by default, but when i invoke the function generateNewArray() i would like the value of my variable to change as well. Do you know how to do it? Thank you for the support.
I don't understand exactly what it is you want. Can you add some example code to your question showing which sequence of function invocations and values you'd like?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.