javascript - ES6 class methods not returning anything inside forEach loop -


for reason method gettwo() inside pollclass won't return 2 undefined. if put return statement outside .foreach() loop value 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 issue closure, es 6, or whole other issue?

an arrow function still function, , you're returning foreach callback function, not gettwo, have return gettwo function well.

it's not quite clear why use loop check in way, concept like

gettwo() {     var n = 0;     this.nums.foreach(num => {       if (num === 2) n = num;     })     return n; // returns gettwo()   } 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -