我有看起来像这样的方法:JS摆脱功能
return AddedSoftware (software) {
this.softwares.map(function(soft) {
if(soft.id == software) {
return software.name;
}
})
}
所以,我怎么会分手,当现在soft.id == software
它遍历整个softwares
它返回之前返回!
我有看起来像这样的方法:JS摆脱功能
return AddedSoftware (software) {
this.softwares.map(function(soft) {
if(soft.id == software) {
return software.name;
}
})
}
所以,我怎么会分手,当现在soft.id == software
它遍历整个softwares
它返回之前返回!
你会使用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.
的'.MAP()'函数是错误的选择; '.find()'可能是你想要的,而不是一个简单的'for'循环。 – Pointy
使用原生循环到'.map'? – TomIsion