0

I previous asked how to import variables values from one JS file into another and perhaps this example may make it more clear as what I am trying to achieve.

   //NumbersFile.js 
   myfirstnumbersarray = new Array();

   myfirstnumbersarray[0] = ThisChangingValue;

Now I have a populated array in my NumbersFile.js (12,89,54,23,11 ...& so on), in a second JS file called AddThemUp.js, I want to import the values of myfirstnumbersarray and perform a simple addition function.

    //AddThemUpFile.js
    //I want to add myfirstnumbersarray[0]+myfirstnumbersarray[3]
    var sum1 = myfirstnumbersarray[0]+myfirstnumbersarray[3];
    (var sum1 should equal 66 (12+54))

How does myfirstnumbersarray get imported into the AddThemUp file.js, thanks....

3
  • 1
    if you are running this in a browser then include script tags pointing to both files (in order) into your html page Commented Oct 3, 2013 at 19:52
  • I asked that question as well, found the answers to be web based. However, my app is not web based. Commented Oct 3, 2013 at 20:30
  • @ddawson7: If it's not "web-based", then what is it? Commented Oct 4, 2013 at 15:48

1 Answer 1

3

If your variables are global, they are already available in every JS file or script tag on your site, no coding necessary. Global vars are attached to the window object, and aren't stuck within a particular file.

If your vars are not global (they are local if defined inside a function) You can pass them to another function in another file, so long as the function is global, or is available within your current scope. (JavaScript uses function scoping).

If you are using Node.js you can just:

var file = require('./yourfile.js');

or for non-js files:

fs = require('fs');
fs.readFile('/etc/hosts', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  console.log(data);
});
Sign up to request clarification or add additional context in comments.

10 Comments

This isn't a website, it is in an application...Dave
@ddawson7 -- "A rose by any other name would smell as sweet."
This is not on a website, this is being used in an application to crunch numbers, no website, no internet involved.....
Then I suppose you are using Node.js -- which uses require() to get files, like fs = require('fs'); so you can just require() your file and it will be there.
I do not know how to use Node.js, I do not know how to make my simple example work. I would be grateful if you could write (show me) just how to export values of an array from one JS file into another.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.