ES6 class methods not returning anything inside forEach loop(ES6 类方法在 forEach 循环中不返回任何内容)
问题描述
由于某种原因,PollClass
中的方法 getTwo()
不会返回 2
,而是返回 undefined
.如果我将 return
语句放在 .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 循环中不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ES6 类方法在 forEach 循环中不返回任何内容


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01