由于某种原因,PollClass
中的方法getTwo()
将不返回2
,而是undefined
。如果我将return
语句放在.forEach()
循环之外,则会返回一个值。ES6类方法在forEach循环内不返回任何东西
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还是其他问题?
目前尚不清楚,你想,如果回到什么'this.nums'没有2,或者它不止一个2.不管怎样,你最好使用'.some'而不是'forEach'。 – raina77ow
'forEach'不会返回任何东西。这不是'for'循环 – Redu
*“这是关闭,ES 6还是其他问题?”*都不是。内部函数不能让外部函数返回一些东西。 –