遍历学生对象grades数组后输出末尾出现undefined,求问题原因
为什么forEach遍历数组后输出末尾多了个undefined?
我正在参加在线课程,练习forEach方法与对象的结合,编写了一个接收对象、遍历其数组元素的函数,不想修改现有遍历逻辑,但运行代码后输出结果末尾多了个undefined,正常应该只输出数组里的四个数字,请求排查问题。
我的代码:
let student = { firstName: "Sam", //string lastName: "Doe", // string hasGraduated: false, // boolean age: 21, // number grades: [15, 18, 14, 17], // array of numbers interests: ["computers", "books"] // array of strings }; function showContent(obj){ obj.grades.forEach(function(grade){ console.log(grade); }) } console.log(showContent(student));
问题原因:
showContent函数内部只执行了forEach遍历打印操作,没有定义返回值,JavaScript中无返回值的函数默认返回undefined- 你用
console.log(showContent(student))调用函数时,会先执行函数内部的四次console.log输出成绩,然后再把函数的返回值undefined打印出来,所以末尾多了这个额外输出
解决方法:
直接调用函数即可,不需要用console.log包裹:
showContent(student);
这样执行后就只会输出数组里的四个数字,不会出现末尾的undefined。
内容的提问来源于stack exchange,提问作者BeginnerLeveljavascript
相关产品推荐
相关产品推荐

