出于某种原因,PollClass
中的方法 getTwo()
不会返回 2
,而是返回 undefined
。如果我将 return
语句放在 .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 还是其他问题?
最佳答案
箭头函数仍然是一个函数,您仅从 forEach 回调函数返回,而不是从 getTwo 返回,您还必须从 getTwo
函数返回。
不太清楚为什么要使用循环以这种方式检查某些内容,但概念类似于
getTwo() {
var n = 0;
this.nums.forEach(num => {
if (num === 2) n = num;
})
return n; // returns something from getTwo()
}
关于javascript - ES6 类方法在 forEach 循环内不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39645392/