2016-11-06 75 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'? – TomIsion

回答

6

你會使用find()代替

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; 
} 

這會給你的第一個對象符合條件。然後您可以從該對象獲得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