【问题标题】:abstract javascript code into ES6 function将 JavaScript 代码抽象为 ES6 函数
【发布时间】:2018-07-31 05:43:42
【问题描述】:

我有一些正在运行的代码,但我想将其抽象为一个功能组件,我可以在脚本的其他地方使用它。我收到一个未定义的错误:

这行得通:

//add an index to each element
    var items = learning_check.map(function(el,i) {
      var o = Object.assign({}, el);
      o.key = i;
      return o;
    });

这不是:

const addIndex = (a) => {
  console.log('addIndex initiated')
  a.map = (el,i) => {
    var o = Object.assign({}, el);
    o.key = i;
    return o;
  }
}

调用

const mItems = addIndex(learning_check); // initiated
console.log('mItems: ' + mItems); // undefined

【问题讨论】:

  • 你不是 returning map 的结果 - addIndex 没有 return 声明。
  • 在你的第二个代码块中,你不是在调用 map,而是在覆盖它。

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

首先,我想说你走在正确的轨道上。你错过了两件事。

您需要调用map 而不是重新分配它,例如a.map(...) 而不是a.map = ...。而且,您需要从您的addIndex 函数返回map 的结果。像这样,

const addIndex = (a) => {
  console.log('addIndex initiated');
  // Notice the return
  return a.map((el, i) => { // See how we call map here
    var o = Object.assign({}, el);
    o.key = i;
    return o;
  });
}

// Mock
const learning_check = [{
  id: "abcde"
}, {
  id: "fghij"
}];

const mItems = addIndex(learning_check); // initiated
console.log('mItems: ' + JSON.stringify(mItems));

我会建议您在此处简化代码,如果您愿意,可以使用它

const addIndex = (a) => {
  console.log('addIndex initiated')
  return a.map((el, i) => Object.assign({
    key: i
  }, el));
}

// Mock
const learning_check = [{
  id: "abcde"
}, {
  id: "fghij"
}];

const mItems = addIndex(learning_check); // initiated
console.log('mItems: ' + JSON.stringify(mItems));

【讨论】:

  • 这个效果很好,谢谢你的解释,我现在明白了
【解决方案2】:

您的代码中有两个错误
1) 你没有从函数中返回任何东西。
2) 你没有调用map 函数。

const addIndex = (a) => {
  console.log('addIndex initiated')
  return a.map((el, i) => {
    var o = Object.assign({}, el);
    o.key = i;
    return o;
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2017-12-06
    • 2018-12-04
    相关资源
    最近更新 更多