How To Assign Variable To External Array File?
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!
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM