2017-01-27 1 views
0

콘솔에 항목을 선택한 로그 I, 각 고객의 이름, 아이디, 계좌 번호, 주소를 가지고 있으며, 계정 정보를 배열라는 고객이 : 지금은 반복하려고 해요에 대한배열을 반복 처리하고

var customers = [ 
    { 
     "name": "John Doe", 
     "id": 1205, 
     "accountNumber": 187456, 
     "address": { 
      "houseNumber": 12, 
      "streetName": "made up street", 
      "postCode": "WE1 234", 
      "area": "Birmingham" 
     }, 
     "hasCurrentAccount": true, 
     "hasLoan": false, 
     "hasMortgage": true 
    }, 
    { 
     "name": "Jane Doe", 
     "id": 1304, 
     "accountNumber": 123456, 
     "address": { 
      "houseNumber": 420, 
      "streetName": "The Street", 
      "postCode": "DE3 456", 
      "area": "Wolverhampton" 
     }, 
     "hasCurrentAccount": false, 
     "hasLoan": true, 
     "hasMortgage": false 
    } 
]; 

이 배열을 통해 이름과 ID를 검색하고 콘솔에 인쇄 :

var info = customers; 
for (var i in info) 
{ 
    var id = info.id; 
    var name = info.name; 
    console.log('Here are your current customers' + id + ' ' + name); 
} 

하지만 난 그냥 얻을

Here are your current customers undefined undefined 

나는 여러 가지 방법을 시도해 봤지만 제대로 작동하지 않는 것 같습니다. 아무도 도와 줄 수 있습니까?

+0

귀하의 예제에는 JSON이 없습니다. 객체의 (JavaScript) 배열 만. 힌트 :'for (var i in info) '를 사용하고 있지만'i'를 사용하여 아무 것도하지 않습니다. –

+0

원래 JSON을 사용하고 있었지만 어레이로 바꿨다는 것을 알아야했습니다! 지금 수정하겠습니다. –

+0

'var id = i.id; ' – nicovank

답변

0

Array.forEach 함수를 사용하여 배열을 반복 할 수 있습니다. 각 항목에서 값을 기록 할 수있는 함수를 실행합니다.

예 :

var customers = [ 
 
    { 
 
     "name": "John Doe", 
 
     "id": 1205, 
 
     "accountNumber": 187456, 
 
     "address": { 
 
      "houseNumber": 12, 
 
      "streetName": "made up street", 
 
      "postCode": "WE1 234", 
 
      "area": "Birmingham" 
 
     }, 
 
     "hasCurrentAccount": true, 
 
     "hasLoan": false, 
 
     "hasMortgage": true 
 
    }, 
 
    { 
 
     "name": "Jane Doe", 
 
     "id": 1304, 
 
     "accountNumber": 123456, 
 
     "address": { 
 
      "houseNumber": 420, 
 
      "streetName": "The Street", 
 
      "postCode": "DE3 456", 
 
      "area": "Wolverhampton" 
 
     }, 
 
     "hasCurrentAccount": false, 
 
     "hasLoan": true, 
 
     "hasMortgage": false 
 
    } 
 
]; 
 

 
customers.forEach(function(item) { 
 
    console.log('Here are your current customers', item.id, item.name); 
 
})

+0

문제가 무엇인지, 해결 방법을 설명하면 게시물이 다른 사람들에게 훨씬 유용 할 것입니다. 코드 만 응답은 일반적으로 낮은 품질로 간주됩니다. –

+0

피드백에 감사드립니다. – Giladd

+0

@Giladd 이것은 매력처럼 작동합니다! 그래서 배열의 각 항목에 대해이 작업을 수행 할 수 있습니까? –

0

이렇게하면 문제가 해결됩니다.

for (a in customers){ 
console.log('Here are your current customers' + a + ' ' + customers[a].name); 
} 
+0

문제가 무엇인지, 해결책이 어떻게 해결되는지에 대해 설명하면 게시물이 다른 사람들에게 훨씬 유용 할 것입니다. * "시험해보십시오"*는 단지 불필요한 진술 일뿐입니다. –