ES6 class methods not returning anything inside forEach loop

前端 未结 2 411
無奈伤痛
無奈伤痛 2020-12-22 06:20

For some reason the method getTwo() inside the PollClass won\'t return 2 but undefined. If I put the return

相关标签:
2条回答
  • 2020-12-22 07:00

    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);
    }
    
    0 讨论(0)
  • 2020-12-22 07:06

    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()
      }
    
    0 讨论(0)
提交回复
热议问题