Search code examples
javascriptarraysreadability

Separate arrays from main script file


I'm working on a Javascript code that generates random text from smaller sets of strings. The problem is that to make the code easy to read and to expand, I definitely have to use one line for each string variables.

Something like this, very broadly.

var array = [
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
"text",
...
]

var array_b = [
//(the same again)
]

var result = array[math.floor(math.random())] + " " + array_b[math.floor(math.random())] 

Needless to say, it's quite uncomfortable. Not impossible to get used to, obviously; but if it's possible, I'd get rid of those long arrays.

Is there a way for it? Putting them into a different file, calling them from another script of another page maybe? Or anything?


Solution

  • You can put the array into a JSON(JavaScript Object Notation) file, then use an ajax request to load them

    data.json

    ["text","text","text","text","text","text","text","text","text","text",...]
    

    main.js

    //if using jQuery
    jQuery.ajax({
      url:"data.json",
      dataType:"json"
    }).then(function(data){
       //'data' will be your array use it
    });
    
    //if not using jQuery
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            //parse the JSON text
            var data = JSON.parse(xmlhttp.responseText);
            //call a function passing it the array
            response(data);
        }
    };
    xmlhttp.open("GET", "data.json");
    xmlhttp.send();
    
    function response(data){
       //data will be your array use it
    }
    

    You can also just add them to a separate js file and add a second <script> element

    data.js

    var data =["text","text","text","text","text","text","text","text","text","text",...]
    

    main.html

    <head>
        <script src="data.js"></script>
        <script src="main.js"></script>
    </head>