2016-11-06 70 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