-2

I'm new to JavaScript so sorry for the amateur question but I feel as through the answer would help to make more sense of the course material, and assignments, in my online course. Here it is. When I write console.log like this:

var getKeys = function(objOne){
  for(var property in objOne){
    console.log(property);
  }
};

console returns: "name" "age"

...but if I change console.log to "return", like this:

var getKeys = function(objOne){
  for(var property in objOne){
    return property;
  }
};

output returns: "name"

Why are the returns different?

4

5 回答 5

1

因为return退出函数。您在第一个属性上退出函数,因此它只有一个。

MDN return

return 语句结束函数执行并指定要返回给函数调用者的值。

于 2015-07-15T01:15:20.463 回答
0

根据规范,(强调我的)

return语句会导致函数停止执行并向调用者返回一个值。

所以你的for...in循环永远不会达到第二次迭代。

于 2015-07-15T01:15:43.477 回答
0

console.log并且return是完全不同的东西。

对于第一种情况,您会看到

"name"
"age"
> undefined 

因为您告诉控制台显式记录键,但是在第二种情况下,使用return关键字,您告诉函数终止并返回值"name",这就是为什么您只看到

> "name"
于 2015-07-15T01:15:55.337 回答
0

console.log()将打印到控制台您传入的参数,其中 asreturn停止执行您的函数并返回您告诉它的任何内容。

于 2015-07-15T01:15:57.263 回答
0

一旦函数命中返回语句,它将停止执行;所以在第一个例子中,它循环通过两者。在第二个中,它点击返回语句并说:“好的,我完成了。”

于 2015-07-15T01:16:22.980 回答