Javascript 如何在jQuery中通过字符串值调用变量?

Javascript 如何在jQuery中通过字符串值调用变量?,javascript,jquery,variables,Javascript,Jquery,Variables,我有一个数据集 var data1 = {values:[ { X: "33", Y: 12 }, .... ]}; var data2 = { values:[ { X: "Jan", Y: 2 }, ... ]}; 我想通过加载适当的数据集 $(document).ready(function() { $(".test").click(function(){ var data = $(this).val() // the value will be data

我有一个数据集

var data1 = {values:[
  { X: "33", Y: 12 },
  ....
  ]};
var data2 = { values:[
  { X: "Jan", Y: 2 },
  ...
  ]};
我想通过加载适当的数据集

$(document).ready(function() {
  $(".test").click(function(){
  var data = $(this).val() // the value will be data1 or data2
           // how can I make the data a JSON equal to data1 or data2 instead of
           // assigning the static value of $(this).val() to it.
  }
});
如何从静态值创建
var数据?

不要

data1
data2
作为对象的属性,并使用方括号成员运算符访问它们

var dataset = {

    data1: {
        values: [{
            X: "33",
            Y: 12
        }, ....]
    }
    data2: {
        values: [{
            X: "Jan",
            Y: 2
        }, ...]
    };
}


虽然如果您的
data1
data2
是全局变量,但您可以从
窗口
对象以相同的方式访问它们

var data = window[$(this).val()]
但是像
dataset
这样的对象仍然比一堆全局对象好

var data = window[$(this).val()]