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.

Share Improve this question edited Oct 22, 2017 at 5:07 Mihai Alexandru-Ionut 48.4k14 gold badges105 silver badges132 bronze badges asked Oct 21, 2017 at 13:42 NoChanceNoChance 5,7724 gold badges36 silver badges48 bronze badges 2
  • 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 with var (or let) 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
Add a ment  | 

1 Answer 1

Reset to default 7

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); 
        }
);

本文标签: javascriptWhy consolelog function returns undefinedStack Overflow