10

I have a project using node.js. It's my first time using nodejs and I want to export an array to my app. Here is some code:

module.exports = { 
    var arrays = [];
    arrays[0] = 'array 0';
    arrays[1] = 'array 1';
    arrays[2] = 'array 2';
    arrays[3] = 'array 3';
    arrays[4] = 'array 4';
    var r_array = arrays[Math.floor(Math.random() * arrays.length)].toString();
}

At the end I want to use the var r_array in my app.js but I don't know how.

Tobias Tengler
  • 5,774
  • 4
  • 18
  • 33
Limatuz
  • 576
  • 2
  • 5
  • 12

3 Answers3

12

You'd want to define a function which returns the randomized portion of the array:

module.exports = {
  getRArray: function() {
    var arrays = [];
    arrays[0] = 'array 0';
    arrays[1] = 'array 1';
    arrays[2] = 'array 2';
    arrays[3] = 'array 3';
    arrays[4] = 'array 4';
    return arrays[Math.floor(Math.random()*arrays.length)];
  }
};

Also you should embed the array into the function so it actually returns something.

FatalMerlin
  • 1,426
  • 2
  • 13
  • 24
4

module.exports needs to be an object.

Perhaps you're looking for something more like:

var arrays = [];
arrays[0] = 'array 0';
arrays[1] = 'array 1';
arrays[2] = 'array 2';
arrays[3] = 'array 3';
arrays[4] = 'array 4';
var r_array = arrays[Math.floor(Math.random()*arrays.length)].toString();

module.exports = r_array;

Please note that this code will only be run once, and that if you're hoping to get a different random value by executing the code multiple times, that you may want to set it up more like:

module.exports = function() {
  return arrays[Math.floor(Math.random()*arrays.length)];
}

so that the Math.random() operation happens over and over.

therobinkim
  • 2,295
  • 12
  • 20
0
var arrays = [];
arrays[0] = 'array 0';
arrays[1] = 'array 1';
arrays[2] = 'array 2';
arrays[3] = 'array 3';
arrays[4] = 'array 4';
var r_array = arrays[Math.floor(Math.random()*arrays.length)].toString();
module.exports = r_array;
feychu
  • 1,154
  • 11
  • 30
  • okay thank you! but i have an additional question. then there is only one random array. how do i have to do it if i want every time another array? :) – Limatuz Dec 19 '16 at 09:06
  • You should check @therobinkim answer. But note that you are not going to get a random array every time if you are applying `toString` to the result. This means the value will be translated into a string, so you'll get a random string every time. – feychu Dec 19 '16 at 09:14