2011-12-05 84 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