JS突破功能

Jam*_*mie 1 javascript ecmascript-6

我有一个看起来像这样的方法:

return AddedSoftware (software) {
    this.softwares.map(function(soft) {
        if(soft.id == software) {
            return software.name;
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

那么我怎么能打破并返回soft.id == software现在它softwares在它返回之前循环整个!

chr*_*con 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;
}
Run Code Online (Sandbox Code Playgroud)

这将为您提供符合条件的第一个对象.然后software.name,您可以从该对象获取.

摘自文档:

find()方法返回数组中第一个满足提供的测试函数的元素的值.否则返回undefined.