我有看起來像這樣的方法: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