如何在JavaScript中声明和访问对象数组?

Pro*_*ofK 1 javascript

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

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();
});
Run Code Online (Sandbox Code Playgroud)

ick*_*fay 5

您正确定义了数组,但这不是您在JavaScript中迭代数组的方式.试试这个:

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

这样做的更好(虽然有点慢)的方法只适用于较新的浏览器Array.forEach:

function templateOptionList() {
    templates.forEach(function(t) {
        console.log(t.post_title);
    });
}
Run Code Online (Sandbox Code Playgroud)