2016-11-06 4 views
1

에서이처럼 보이는 방법을 브레이크 :JS는 내가있어 기능

return AddedSoftware (software) { 
    this.softwares.map(function(soft) { 
     if(soft.id == software) { 
      return software.name; 
     } 
    }) 
} 

그래서 휴식과 soft.id == software 지금 루프 때 반환하기 전에 전체 softwares을 통해 반환 할 수 방법!

+0

은'.MAP() '함수는 잘못된 선택이다; '.find()'는 아마도 여러분이 원하는 것일 것입니다. 간단한 for 루프가 아닙니다. – Pointy

+0

'.map'에 대한 네이티브 for 루프를 사용합니까? – TomIsion

답변

6

대신

return function AddedSoftware (software) { 
    let res = this.softwares.find(soft => soft.id == software); 
    // return the software's name if there's a match, or undefined 
    return res ? res.name : res; 
} 

이 당신에게 당신의 상태와 일치하는 첫 번째 개체를 줄 것이다 find()을 사용합니다. 그러면 해당 오브젝트에서 software.name을 얻을 수 있습니다. 워드 프로세서에서

발췌 :

The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

+0

OP의 기능이 발견 된 항목의 "이름"속성을 반환하려고했습니다. – Pointy

+0

답변을 편집했습니다. @Pointy – baao

+1

고마워요. 거의 혼자했는데, 사람들이 무례하다고 생각할 까봐 두렵습니다. – Pointy