JavaScript回调混淆行为

JavaScript回调混淆行为,javascript,arrays,methods,callback,arrow-functions,Javascript,Arrays,Methods,Callback,Arrow Functions,在JavaScript中编写回调函数时遇到问题,该函数返回一个映射数组,其中的每个数字递增一 arr=[1,2,3,4]; const each=(元素,cb)=>{ for(设i=0;i{ 常量mappedArr=[]; 每个(元素,项目=>{ mappedArr.push(cb(项目)); }); 返回mappedar; }; 常数cb=(e)=>{ e+=1; } const newArr=map(arr,cb); console.log(newArr)/[undefined,undef

在JavaScript中编写回调函数时遇到问题,该函数返回一个映射数组,其中的每个数字递增一

arr=[1,2,3,4];
const each=(元素,cb)=>{
for(设i=0;i{
常量mappedArr=[];
每个(元素,项目=>{
mappedArr.push(cb(项目));
});
返回mappedar;
};
常数cb=(e)=>{
e+=1;
}
const newArr=map(arr,cb);

console.log(newArr)/[undefined,undefined,undefined,undefined]
您的
cb
目前没有返回任何内容,因此返回值默认为
undefined
。改为使用带有隐式返回(no
{
}s)的箭头函数,以便返回递增的值

另外,尽量避免隐式创建全局变量(使用
arr
):

const arr=[1,2,3,4];
const each=(元素,cb)=>{
for(设i=0;i{
常量mappedArr=[];
每个(元素,项目=>{
mappedArr.push(cb(项目));
});
返回mappedar;
};
常数cb=e=>e+1;
const newArr=map(arr,cb);

console.log(newArr)
cb
函数中返回缺失。检查此项:

arr=[1,2,3,4];
const each=(元素,cb)=>{
for(设i=0;i{
常量mappedArr=[];
每个(元素,项目=>{
mappedArr.push(cb(项目));
});
返回mappedar;
};
常数cb=(e)=>{
返回e+=1;
}
const newArr=map(arr,cb);

console.log(newArr)/[undefined,undefined,undefined,undefined]
cb函数没有返回任何东西-也就是说,这相当于让
返回undefined
-也许你想要
常量cb=(e)=>e+1
(隐含返回)或
const cb=(e)=>{returne e+1;}
@SeanValdiva:除了其他答案之外,您还可以归结为
const cb=e=>e++