ES6类方法没有返回forEach循环中的任何内容 [英] ES6 class methods not returning anything inside forEach loop

查看:291
本文介绍了ES6类方法没有返回forEach循环中的任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因, PollClass 内的方法 getTwo()将不会返回 2 未定义。如果我在 .forEach()循环之外的返回语句中,则返回一个值。

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

这是关闭,ES 6或其他一个问题问题?

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

推荐答案

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

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()
  }

这篇关于ES6类方法没有返回forEach循环中的任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆