Why does every JS object have one undefined proper

2020-05-01 03:52发布

let obj = {a:'a',b:'b'};
for (let p in obj){
   console.log(p);
}

Output:

a 
b
undefined

What's up with the undefined property?

1条回答
神经病院院长
2楼-- · 2020-05-01 04:45

That's not a property, it's the return of function that developer tools prints.

Example:

console.logger = function(p){
           console.log(p);
           return "logged"
      }
var obj = {a:'a',b:'b'};
for (var p in obj){
   console.logger(p);
}

a          // logs the property
b          // logs the property
"logged"   // logs the return of logger function, undefined in case nothing's returned
查看更多
登录 后发表回答