2014-01-19 71 views
0

我試圖訪問一個數組內的對象的屬性之一。這是我如何設置的。如何從數組中的對象訪問屬性?

var 2002 = [{"st_as_str":"01006000102","parm_desc":"ALKALINITY, TOTAL","sub":"ALKALINITY","is_fil":false,"is_reac":false,"date":"2002-09-02","time":"16:45","field_num":70237,"lims_r":"","result":137.0,"val_qual":"","ana_meth":"E3218A","unit":"MILLIGRAM PER LITER"}, 

{"st_as_str":"01006000102","parm_desc":"ALKALINITY, TOTAL","sub":"ALKALINITY","is_fil":false,"is_reac":false,"date":"2002-09-08","time":"14:30","field_num":70240,"lims_r":"","result":142.0,"val_qual":"","ana_meth":"E3218A","unit":"MILLIGRAM PER LITER"}] 
//These two lines are actually one. I broke them up to make this somewhat readable. Also, this is a portion of the file. 

我一直在試圖訪問這樣的屬性:

alert(2002[0].parm_desc);

如:alert(array[object at this index].thisproperty)雖然它似乎並不奏效。這是我的更多代碼。

<script> 
     function getScript(url, callback) { 
      var script = document.createElement('script'); 
      script.type = 'text/javascript'; 
      script.src = url; 

      script.onreadystatechange = callback; 
      script.onload = callback; 

      document.getElementsByTagName('head')[0].appendChild(script); 
     } 

     //this works and I am getting the alerts 
     getScript('./analysis_valqualifi.js', function(){ 
      alert("Analysis Method: " + analysis_method[0][1]); 
      alert("Lims_ValQualifi: " + lims_valqualifi[0][1]); 
     }); 

     //this isn't working 
     getScript('./2002_results.js', function(){ 
      alert(2002[0].parm_desc); 
     }); 
    </script> 

第2個警報後還有15-20秒延遲我的其他腳本運行之前,所以我敢肯定JavaScript被讀取文件和我的語法不正確。

+1

變量不能以數字開頭。 – elclanrs

回答

1

您的變量2002是違法的。如果您嘗試直接在Chrome的開發者工具控制檯的第一線(S),它會立即報告如下:

var 2002 = [{"st_as_str":"01006000102","parm_desc":"ALKALINITY, TOTAL","sub":"ALKALINITY","is_fil":false,"is_reac":false,"date":"2002-09-02","time":"16:45","field_num":70237,"lims_r":"","result":137.0,"val_qual":"","ana_meth":"E3218A","unit":"MILLIGRAM PER LITER"}, ... 

SyntaxError: Unexpected number 

如果單純的前綴,它有一個字符,例如:

var s2002 = [{"st_as_str":"01006000102","parm_desc":"ALKALINITY, TOTAL","sub":"ALKALINITY","is_fil":false,"is_reac":false,"date":"2002-09-02","time":"16:45","field_num":70237,"lims_r":"","result":137.0,"val_qual":"","ana_meth":"E3218A","unit":"MILLIGRAM PER LITER"}, {"st_as_str":"01006000102","parm_desc":"ALKALINITY, TOTAL","sub":"ALKALINITY","is_fil":false,"is_reac":false,"date":"2002-09-08","time":"14:30","field_num":70240,"lims_r":"","result":142.0,"val_qual":"","ana_meth":"E3218A","unit":"MILLIGRAM PER LITER"}] 

這工作得很好。請參閱this post以獲取變量名稱規則的完整摘要。

+0

謝謝,scotth。我會投你一票,但我沒有代表。希望最好的答案是夠好的。 – user3210944

1

需要考慮的幾點:

變量名稱不能以數字開頭。例如,將其更改爲「data2002」。

JSON對象中的屬性可以是數字,但這會在您的數組中創建空隙。你的代碼中沒有這個問題,但只是把它放在那裏。

如果屬性名稱爲空格,例如{'Test Mode':true},您可以使用以下語法訪問它:

var testmode = obj['Test Mode']; 
+0

非常感謝。不幸的是,我沒有代表投票給你,但。 – user3210944