2015-06-26 39 views
1

我試圖迭代JavaScript數組並將單個對象值顯示爲警報。基本上,數組包含類型person從Javascript獲得n值數組

"person" : { 
    "id": String, 
    "name": String, 
    "address": String 
} 

的對象和我的數組如下:

//This is where I get my array from the code behind. It's not empty. I checked 
var obj = JSON.parse(val) 

obj.forEach(function (entry) { 
    console.log(entry); 
    //This prints the entire array and its objects 
}); 

我想是不是打印整個數組,我想打印:

obj.forEach(function (entry) { 
    console.log(entry[1].name); 
    console.log(entry[1].address); 
    //This prints the entire array and its objects 
}); 

我應該對我的代碼應用哪些更改?

+0

剛剛擺脫那些 '[1]',作爲入門已經是一個元素的陣列;) – DRC

回答

1

在foreach裏面,entry只是一個人的要素,使用:

obj.forEach(function (entry) { 
     console.log(entry.name); 
     console.log(entry.address); 
}); 
1

在.forEach功能可以採取指標和元素 -

$.each(obj, function(index, element) { 
... 
}); 

所以,你既可以使用元素,或者使用索引。

1

如果你不使用香草JS需要,你可以使用jQuery:

$(obj).each(function(index) { 
    console.log($(this).name); 
    console.log($(this).address); 
}); 

或者

$(obj).each(function(index) { 
    console.log($(obj)[index].name); 
    console.log($(obj)[index].address); 
});