ES6 class methods not returning anything inside forEach loop

前端 未结 2 486
無奈伤痛
無奈伤痛 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条回答
  •  Happy的楠姐
    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()
      }
    

提交回复
热议问题