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
come from? Thanks.
arrayOfObjects.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); } );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.