Ad

How To Assign Variable To External Array File?

- 1 answer

In a js script (part of a Githubpages project), I currently have a variable defined as an array:

var myArray= [
 'one string',
 'two string',
 'red string',
 'blue string',
];

The thing is, my real array declared as the variable's value is very long, with plenty of long strings. I want to put the array in a separate file and still declare the variable as that array. Is there some way to do this by referencing the location of the file,

Like,

In folder "arrays", filename "dr.suess":

  [
  'one string',
  'two string',
  'red string',
  'blue string',
   ];

In my JavaScript:

var myArray = https://user.github.io/arrays/dr.suess

Or is this just not gonna work? Preferably an answer not with jQuery, cause I don't understand it. Thanks for the help!

Ad

Answer

Take a look at the following .html file

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>

    <script>
      const arr = [1,2,3]
    </script>

    <script>
      console.log(arr)
    </script>
</head>
<body>


</body>
</html>

Inside the <head> tag I have two <script> tags. Despite being separate tags, they both run on the same page and in the order they appear on the page, meaning first, const arr = [1,2,3] will evaluate and create variable named arr, then console.log(arr) will log this variable

You can move first script in one file and second script in another file, then include these files in <script> tags, like this

<script src="arrays/myArrayFile.js"></script>
<script src="main.js"></script>

Pay attention to the path of included files

Ad
source: stackoverflow.com
Ad