2011-12-05 103 views
1

我有以下代码,目的是定义和使用对象列表,但我得到'undefine'为post_title。我究竟做错了什么?我不想将数组命名为对象的属性,我只想要一个对象的集合/数组。如何在JavaScript中声明和访问对象数组?

var templates = [{ "ID": "12", "post_title": "Our Title" } 
    , { "ID": "14", "post_title": "pwd" }]; 
function templateOptionList() { 
    for(var t in templates) { 
     console.log(t.post_title); 
    } 
} 
$(function() { 
    templateOptionList(); 
}); 
+0

我希望你不介意,但我已编辑问题标题/标记以移除对JSON的引用(这不是JSON:JSON是对象/数组数据的字符串表示形式,它看起来像JavaScript中的对象/数组字面语法)。 – nnnnnn

回答

5

你正在定义数组,但这不是你在JavaScript中迭代数组的方式。试试这个:

function templateOptionList() { 
    for(var i=0, l=templates.length; i<l; i++) { 
     var t=templates[i]; 
     console.log(t.post_title); 
    } 
} 

做的更好(虽然有点慢)的方式这一点,只能在新的浏览器是使用Array.forEach

function templateOptionList() { 
    templates.forEach(function(t) { 
     console.log(t.post_title); 
    }); 
} 
+0

浏览器必须多少新?我在这里瞄准WordPress的市场,谁知道他们的目标是多么落后。 – ProfK

+0

@ProfK:在[here](http://kangax.github.com/es5-compat-table/)中查找'Array.prototype.forEach'。它看起来像大多数当前的浏览器支持它,除了IE 8和以下。 – icktoofay

+0

[换句话说](http://gs.statcounter.com/#browser_version-ww-monthly-201011-201111)有相当比例的用户不能使用'Array.prototype.forEach' ... – nnnnnn