Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JS variable name to function

So here is what I am trying to do:

  1. My variable named data_1 is set.

    var data_1 = {
      "y_legend": {
        "text": "# of Patients",
        "style": "{font-size: 20px; color: #778877}"
      },
      "x_legend": {
        "text": "AUG 09 - OCT 09",
        "style": "{font-size: 20px; color: #778877}"
      }
    };
    
  2. In a drop down a user selects an option with the value of data_1 that calls load('data_1').

    function load(data)
    {
      tmp = findSWF("my_chart");
      x = tmp.load( JSON.stringify(data) );
    }
    

My Problem: I'm selecting an option with the value data_1 and not the variable itself. So in my function load('data_1'), when I alert(data) I get data = 'data_1'.

So how do I get the contents of my variable data_1 in my load function by passing only the name of the string?

like image 317
Fostah Avatar asked Sep 02 '09 18:09

Fostah


People also ask

Can a function and a variable have the same name in JS?

What is it you would expect? Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable.

How do you name variables and functions in JavaScript?

Naming ConventionsVariable and function names written as camelCase. Global variables written in UPPERCASE (We don't, but it's quite common) Constants (like PI) written in UPPERCASE.

Can you pass a variable to JavaScript?

Javascript pass by value:In javascript pass by value, the function is called by directly passing the value of the variable as the argument. Therefore, even changing the argument inside the function doesn't affect the variable passed from outside the function.


2 Answers

var data_1 = { /* data goes here */ };

var data_choices = {1: data_1, 2: data_2, /* and so on */};

var load = function (data) {
    // data is "1", "2", etc. If you want to use the full data_1 name, change
    // the data_choices object keys.

    var tmp = findSWF("my_chart");
    var x = tmp.load( JSON.stringify(data_choices[data]) );
}
like image 89
John Millikin Avatar answered Sep 20 '22 05:09

John Millikin


If it's a global variable, you can reference it with

window['the_variable_name']

E.g.

function load(data)
{ 
  tmp = findSWF( "my_chart" ); 
  x = tmp.load( JSON.stringify( window[data] ) ); 
}
like image 41
jimr Avatar answered Sep 19 '22 05:09

jimr