Ostrov Ostrov - 1 year ago 59
Javascript Question

How to force function to create global variable

How can I force function to create global variable? I have this code:

url: 'https://dl.dropboxusercontent.com/s/11ofmbg4d4y3gb0/zakaznice_tyden.csv',
dataType: 'text',

function successFunction(data) {
var promenna = data.replace(/\n/g,";").split(";");
var result = [];
for (var i = 0; i < promenna.length; i+=2) {
var line = [];
for (var i = 0; i < result.length; i += 1){
$("#tyden" + i + "").append(result[i][0]);
$("#tyden" + i + "kolik").append(result[i][1]);

It loads csv file and create array from it. How can I make the array "line" globaly reachable?

Answer Source

Scope It Outside Function Scope

The most common approach might be to simply declare it outside of the scope of a function if this is an option :

// This will be globally accessible from any child functions, etc.
var array = [];

function example(){
    // Your code here can access the array as expected

Implicit Global Declaration

If you want to declare a variable with global scope, just omit the var when declaring it, which will implicitly create it globally :

function example(){
    // This will be a global variable
    array = [];

Note: This will not work within strict mode, which does away with implicit globals. You can read more on about this approach here.

Storing the Variable

Another great approach would be to simply store the object as a property on the window object and access it from there as mentioned in Pamblam's answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download