JavaScript回调混乱行为

时间:2018-06-29 01:07:30

标签: javascript arrays methods callback arrow-functions

在用JavaScript编写回调函数时遇到麻烦,该函数返回一个映射数组,其中每个数字加1。

arr = [1, 2, 3, 4];

    const each = (elements, cb) => {
      for (let i = 0; i < elements.length; i++) {
        cb(elements[i], i);
      }
    };
    
    const map = (elements, cb) => {
      const mappedArr = [];
      each(elements, item => {
        mappedArr.push(cb(item));
      });
      return mappedArr;
    };



    const cb = (e) => {
      e += 1;
    }


    const newArr = map(arr, cb);
    console.log(newArr) // [ undefined, undefined, undefined, undefined ]

您的耐心已经得到赞赏;我仍在学习并试图理解回调。请帮助我了解我在这里做错了。

2 个答案:

答案 0 :(得分:3)

您的cb目前未返回任何内容,因此返回值默认为undefined。请使用带有隐式返回(无{ } s)的箭头函数,以便返回递增的值。

此外,请尝试避免隐式创建全局变量(使用arr):

const arr = [1, 2, 3, 4];

const each = (elements, cb) => {
  for (let i = 0; i < elements.length; i++) {
    cb(elements[i], i);
  }
};

const map = (elements, cb) => {
  const mappedArr = [];
  each(elements, item => {
    mappedArr.push(cb(item));
  });
  return mappedArr;
};

const cb = e => e + 1;

const newArr = map(arr, cb);
console.log(newArr)

答案 1 :(得分:2)

cb函数中返回丢失的内容。请检查以下内容:

arr = [1, 2, 3, 4];

const each = (elements, cb) => {
  for (let i = 0; i < elements.length; i++) {
    cb(elements[i], i);
  }
};

const map = (elements, cb) => {
  const mappedArr = [];
  each(elements, item => {
    mappedArr.push(cb(item));
  });
  return mappedArr;
};



const cb = (e) => {
  return e += 1;
}


const newArr = map(arr, cb);
console.log(newArr) // [ undefined, undefined, undefined, undefined ]