如何从数组中的对象访问属性?

时间:2014-01-19 20:41:49

标签: javascript arrays object file-io

我正在尝试访问数组中对象的一个​​属性。以下是我设置它的方法。

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正在读取文件及其语法不正确。

2 个答案:

答案 0 :(得分:1)

您的变量2002是非法的。如果您直接在Chrome开发者工具控制台中尝试第一行,它会立即报告以下内容:

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

答案 1 :(得分:1)

需要考虑的一些要点:

变量名称不能以数字开头。因此,例如将其更改为“data2002”。

JSON对象中的属性可以是数字,但这会在数组中产生间隙。你的代码中没有这个问题,只是把它放在那里。

如果属性名称为空格,例如{'Test Mode':true},您可以使用以下语法访问它:

var testmode = obj['Test Mode'];