简体   繁体   English

为什么console.log函数返回undefined?

[英]Why console.log function returns undefined?

 function stringifyObj(parmObj){ s=""; Object.getOwnPropertyNames(parmObj).forEach ( function (val, idx, array) { s+=val + ' -> ' + parmObj[val]+"\\n"; } ) return s; } var arrayOfObjects = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 } ]; console.log( arrayOfObjects.forEach(function(parmArrItem) { const p=stringifyObj(parmArrItem); console.log(p); } )); 

In the code below, 2 objects are displayed fine, but after that I get undefined displayed at the end of the run. 在下面的代码中,2个对象显示正常,但之后我在运行结束时显示undefined Where does the undefined come from? undefined来自哪里? Thanks. 谢谢。

arrayOfObjects.forEach returns nothing. arrayOfObjects.forEach什么都不返回。

So, when you use console.log() for a void function that's you received undefined . 因此,当您使用console.log()获取未定义的void函数时。

forEach method only executes a callback provided function for every item from an array. forEach方法仅对数组中的每个项执行回调提供的函数。

With the other words, the console prints the result of evaluating an expression . 换句话说, console打印评估 表达式的结果。

console.log() is undefined since your function or expression not explicitly return something. console.log()未定义,因为您的函数或表达式未显式返回某些内容。

 function stringifyObj(parmObj){ s=""; Object.getOwnPropertyNames(parmObj).forEach ( function (val, idx, array) { s+=val + ' -> ' + parmObj[val]+"\\n"; } ) return s; } var arrayOfObjects = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 } ]; arrayOfObjects.forEach(function(parmArrItem) { const p=stringifyObj(parmArrItem); console.log(p); } ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM