2015-05-18 143 views
0

我想訪問使用JS的多維數組中的元素。這似乎並不奏效。請幫助多維數組對象

var parsed = ""; 
var myObject = [{ 
    firstname: "Jane", 
    lastname: "Doe", 
    email: "[email protected]" 
}, { 
    firstname: "Ja", 
    lastname: "joe", 
    email: "[email protected]" 
}]; 
for (var prop in myObject) { 
    parsed += prop + ": " + myObject[prop] + "\n"; 
} 
alert(parsed); 
+0

必須循環陣列上,然後通過對象? –

+0

取決於你想要的,但爲了得到一些有意義的輸出(根據你的輸入),你應該訪問'myObject [prop] .firstname/lastname/email'等。 – amdixon

+0

如果它只是一維數組..我得到正確的響應。此代碼拋出以下內容:0 [object Object] 1 [object Object] –

回答

0

你應該遍歷數組和名稱選擇合適的屬性:

var parsed = ""; 
var myObject = [{ 
    firstname: "Jane", 
    lastname: "Doe", 
    email: "[email protected]" 
    }, 
    { 
    firstname: "Ja", 
    lastname: "joe", 
    email: "[email protected]" 
    }, 
]; 
for(var item in myObject) 
{ 
    for (var prop in item) { 
    parsed += prop + ": " + item[prop] + "\n"; 
    } 
} 
0

您需要其他循環遍歷數組元素。

var parsed = ""; 
var myObject = [{ 
    firstname: "Jane", 
    lastname: "Doe", 
    email: "[email protected]" 
}, 
{ 
    firstname: "Ja", 
    lastname: "joe", 
    email: "[email protected]" 
}, 
]; 
for (i = 0; i< myObject.length; i++){ 
    var myobj= myObject[i]; 
    for (var prop in myobj) { 
    parsed += prop + ": " + myobj[prop] + "\n"; 
} 
} 
alert(parsed); 

DEMO

0

這裏是你的代碼片段。
您的基本錯誤是myObject是對象的數組,讓你在你使用此代碼得到什麼錯誤給定索引

var attr, 
     prop, 
     parsed = "", 
     myObject = [ 
      { 
       firstname: "Jane", 
       lastname: "Doe", 
       email: "[email protected]" 
      }, 
      { 
       firstname: "Ja", 
       lastname: "joe", 
       email: "[email protected]" 
      } 
     ]; 


// My object is an array 
myObject.forEach(function(item, index, array) { 

    // Verify to see that the property you want is yours and not inherited 
    for (attr in item) { 
     if (item.hasOwnProperty(attr)) { 
      parsed += attr + ": " + item[attr] + "\n"; 
     } 
    } 

}) 

alert(parsed);