2012-08-17 40 views
0

字符串指标二维表我需要分析一个表,JSON,我发现这个解决方案,它的工作原理:动态地创建在JavaScript中

var tab=[{"value":"1.0","label":"Alabama"},{"value":"2.0","label":"Alaska"},  {"value":"3.0","label":"American Samoa"}]; 
    var myJsonString = JSON.stringify(tab); 
    var jsonData = $.parseJSON(myJsonString); 

问题是,当我宣布动态二维表“选项卡'它不起作用:

var tab_desc1= new Array(3); 
    tab_desc1[0]=new Array(2); 
    tab_desc1[0]["value"]="1.0"; 
    tab_desc1[0]["label"]="Alabama"; 
    tab_desc1[1]=new Array(2); 
    tab_desc1[1]["value"]="2.0"; 
    tab_desc1[1]["label"]="Alaska"; 
    tab_desc1[2]=new Array(2); 
    tab_desc1[2]["value"]="3.0"; 
    tab_desc1[2]["label"]="American Samoa"; 
    var myJsonString = JSON.stringify(tab_desc1);  
    var jsonData = $.parseJSON(myJsonString); 

从逻辑上说,我的声明包含错误,bur我看不到它。 任何帮助!谢谢。

+1

你的内部尺寸不是一个数组,所以不要做'tab_desc1 [0] = new Array()'。它是一个_object_(JS数组没有字符串键),因此将它创建为一个'tab_desc1 [0] = {}' – 2012-08-17 02:20:54

+1

您正在使用带有字符串的数组。如果你想使用字符串使用对象。在你的情况下,你应该一起使用数组和对象。 – 2012-08-17 02:21:09

+0

我正在工作的移动应用程序(jQuery的移动和phoneGap),我需要它与复杂的对象自动完成搜索:http://www.andymatthews.net/code/autocomplete/local_complex.html – 2012-08-17 02:22:45

回答

2
tab_desc1[0] = new Array(2); 

应该

tab_desc1[0] = {}; 

,并与他人相同。

但我不知道将字符串变成字符串然后解析回来的目的。

+0

的情况下运行良好,这是答案,恭喜! – 2012-08-17 02:38:51

1

问题是数组和对象不是一回事。

你的第一个代码创建了一个对象的数组

您的第二个代码创建了一个数组的数组,但随后在这些数组上设置了非数字属性。 JS数组是一种对象,因此设置非数字属性并不是错误,但stringify()将只包含数字属性。你需要这样做:

var tab_desc1 = []; // Note that [] is "nicer" than new Array(3) 
tab_desc1[0] = {}; // NOTE the curly brackets to create an object not an array 
tab_desc1[0]["value"] = "1.0"; 
tab_desc1[0]["label"] = "Alabama"; 
tab_desc1[1] = {}; // curly brackets 
tab_desc1[1]["value"] = "2.0"; 
tab_desc1[1]["label"] = "Alaska"; 
tab_desc1[2] = {}; // curly brackets 
tab_desc1[2]["value"] = "3.0"; 
tab_desc1[2]["label"] = "American Samoa"; 

var myJsonString = JSON.stringify(tab_desc1);  
var jsonData = $.parseJSON(myJsonString); 

你也可以这样做:

var tab_desc1 = []; 
tab_desc1[0] = {"value":"1.0","label":"Alabama"}; 
tab_desc1[1] = {"value":"2.0","label":"Alaska"}; 
tab_desc1[2] = {"value":"3.0","label":"American Samoa"}; 

(另外,为什么字符串化,然后立即解析找回相同的对象?)

+0

因为我从文件中读取数据,我应该浏览它以在数组中插入数据,然后将其解析为JSON(导致脚本需要json格式) – 2012-08-17 02:44:17

+0

感谢您的澄清,您的回复是完美的! – 2012-08-17 02:48:42