js中for与map在返回promise时的区别?-灵析社区

sumous_01

遇到一个问题:下面是拿到一个数组返回,通过遍历返回一个值,我之前习惯用map去遍历。 const getCapture=async ()=>{ let result=await ipcRenderer.invoke('goCapture-event') for(const m of result){ if(m.name==='整个屏幕'){ let str=m.thumbnail.crop({x:0,y:0,width:1200,height:1170}) const imgSrc=str.toDataURL() return imgSrc } } /* result.map(m=>{ if(m.name==='整个屏幕'){ console.log(m) let str=m.thumbnail.crop({x:0,y:0,width:1000,height:1000}) const imgStr=str.toDataURL() return imgStr } }) */ } 这是map的遍历: result.map(m=>{ if(m.name==='整个屏幕'){ console.log(m) let str=m.thumbnail.crop({x:0,y:0,width:1000,height:1000}) const imgStr=str.toDataURL() return imgStr } }) 这样返回的竟然是空, 但是如果用for,就可以正确返回: for(const m of result){ if(m.name==='整个屏幕'){ let str=m.thumbnail.crop({x:0,y:0,width:1200,height:1170}) const imgSrc=str.toDataURL() return imgSrc } } js中for和map还有这区别吗?

阅读量:197

点赞量:0

问AI
map的回调函数内部用return语句,返回给了map内部的匿名函数,外层的getCapture函数没有接到,所以返回的是空,修改成这样接收: //getCapture函数内部 const mappedResult = result.map(m => { if (m.name === '整个屏幕') { console.log(m) let str = m.thumbnail.crop({x: 0, y: 0, width: 1000, height: 1000}) const imgStr = str.toDataURL() return imgStr } return undefined; }); return mappedResult.find(imgStr => imgStr !== undefined);