ES6 class methods not returning anything inside forEach loop

萝らか妹 提交于 2019-11-28 12:30:42

问题


For some reason the method getTwo() inside the PollClass won't return 2 but undefined. If I put the return statement outside the .forEach() loop a value does get returned however.

class Poll {
  constructor(name) {
    this.name = name;
    this.nums = [1, 2, 3];
  }

  getTwo() {
    this.nums.forEach(num => {
      if (num === 2) return num;
    })
  }
}

const newPoll = new Poll('random name');
console.log(newPoll.getTwo()); // returns undefined, not 2

Is this an issue with closure, ES 6, or a whole other issue?


回答1:


An arrow function is still a function, and you're only returning from the forEach callback function, not from getTwo, you have to return from the getTwo function as well.

It's not quite clear why you would use a loop to check for something in that way, but the concept would be something like

getTwo() {
    var n = 0;
    this.nums.forEach(num => {
      if (num === 2) n = num;
    })
    return n; // returns something from getTwo()
  }



回答2:


As adeneo mentioned, you must return from the getTwo function to achieve what you want. Returning from the callback passed into forEach, regardless if its an arrow function or not, doesn't return from forEach itself.

Alternatively to forEach, you can use find which you can write in less code and return directly:

getTwo() {
  return this.nums.find(num => num === 2);
}


来源:https://stackoverflow.com/questions/39645392/es6-class-methods-not-returning-anything-inside-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!