简体   繁体   English

将JS变量名传递给函数

[英]Passing JS variable name to function

So here is what I am trying to do: 所以这就是我想要做的:

  1. My variable named data_1 is set. 我的变量名为data_1已设置。

     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') . 在下拉列表中,用户选择一个data_1的选项,该值选择调用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. 我的问题:我正在选择值为data_1的选项,而不是变量本身。 So in my function load('data_1') , when I alert(data) I get data = 'data_1' . 所以在我的函数load('data_1') ,当我load('data_1') alert(data)我得到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? 那么如何通过只传递字符串的名称来data_1我的加载函数中的变量data_1的内容?

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]) );
}

If it's a global variable, you can reference it with 如果它是全局变量,您可以使用它来引用它

window['the_variable_name']

Eg 例如

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

或者你可以简单地使用

alert(eval(data)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM