admin管理员组文章数量:1332890
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);
}
));
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. Where does the undefined
e from? Thanks.
-
That's not how
forEach
is used. – ibrahim mahrir Commented Oct 21, 2017 at 13:45 -
2
You forgot to declare
s
properly. Any variable that is not declared withvar
(orlet
) is top-level global, and that always is a bug. Static code analysis tools like jshint show you these errors, use them. – Tomalak Commented Oct 21, 2017 at 13:48
1 Answer
Reset to default 7arrayOfObjects.forEach
returns nothing.
So, when you use console.log()
for a void function that's you received undefined.
forEach method only executes a callback provided function for every item from an array.
With the other words, the console
prints the result of evaluating an expression.
console.log()
is undefined since your function or expression not explicitly return something.
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);
}
);
本文标签: javascriptWhy consolelog function returns undefinedStack Overflow
版权声明:本文标题:javascript - Why console.log function returns undefined? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742296582a2448853.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论