ES6 class 方法在 forEach 循环中不返回任何内容

ES6 class methods not returning anything inside forEach loop

出于某种原因,PollClass 中的方法 getTwo() 不会 return 2 而是 undefined。但是,如果我将 return 语句放在 .forEach() 循环之外,一个值会得到 returned。

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

这是闭包问题、ES 6 问题还是其他问题?

箭头函数仍然是一个函数,你只是 return 从 forEach 回调函数,而不是从 getTwo,你必须 return 从 getTwo 函数还有。

不太清楚为什么要使用循环以这种方式检查某些内容,但这个概念类似于

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

正如 adeneo 提到的,您必须从 getTwo 函数中 return 来实现您想要的。从传递给 forEach 的回调返回,无论它是否是箭头函数,return 都不是来自 forEach 本身。

替代forEach,您可以使用find,这样您可以编写更少的代码和直接return:

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