js中for与map在返回promise时的区别?
遇到一个问题:下面是拿到一个数组返回,通过遍历返回一个值,我之前习惯用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还有这区别吗?
回复
1个回答

test
2024-06-21
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);
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容