1

Say I have a file1.js with an array.

var array = [data, more data, ...];

Is there any way to read that array from a different file? If not, what are the conventions for having a big array in a file?

byrass
  • 360
  • 2
  • 12
  • You can read some posts here in stackoverflow: http://stackoverflow.com/questions/9127447/loading-an-array-from-txt-file and http://stackoverflow.com/questions/17901622/how-to-load-data-from-text-file-to-javascript-array, there are more than this. – kikerrobles Sep 04 '15 at 18:51
  • They both use jquery – byrass Sep 04 '15 at 18:59

2 Answers2

2

Well several years ago the way to do so would be make it a global and have to worry about the order your scripts are loaded, which you can still do. However in this day and age, there are several other ways you can do. This is done through some sort of module concept. There's, requirejs, commonjs, browserify, nodejs's native module system and ES6 import/export.

So in most cases, what you would do is something like (keyword like because some do vary) this:

file 1

module.exports.bigArray = [data];

file 2

var bigArray = require('./file1').bigArray;
Christian Grabowski
  • 2,782
  • 3
  • 32
  • 57
-1

You can read it if file1.js is downloaded by the browser before your different file. and your variable array is available.

<script type="text\javascript" src="file1.js"></script>
<script type="text\javascript" src="differentFile.js"></script>

If possible, please namespace them so that array is not in the global scope.

Sachin
  • 901
  • 2
  • 10
  • 23