Javascript 返回对象的javascript函数返回[object Object]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34573792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:34:17  来源:igfitidea点击:

javascript function to return object returns [object Object]

javascript

提问by kilojoules

The intended output of my function is {"name": "bob", "number": 1}, but it returns [object Object]. How can I achieve the desired output?

我的函数的预期输出是{"name": "bob", "number": 1},但它返回[object Object]. 我怎样才能达到预期的输出?

function myfunc() {
   return {"name": "bob", "number": 1};
}
myfunc();

回答by m0meni

Haha this seems to be a simple misunderstanding. You are returning the object, but the toString()method for an object is [object Object]and it's being implicitly called by the freecodecamp console.

哈哈,这似乎是一个简单的误会。您正在返回对象,但对象的toString()方法是[object Object]并且它被 freecodecamp 控制台隐式调用。

Object.prototype.toString()

Object.prototype.toString()

var o = {}; // o is an Object
o.toString(); // returns [object Object]

You can easily verify you actually are returning an object using your own code:

您可以使用自己的代码轻松验证您实际上是在返回一个对象:

function myfunc() {
   return {"name": "bob", "number": 1};
}

var myobj = myfunc();
console.log(myobj.name, myobj.number); // logs "bob 1"

回答by aliasm2k

If you try console.log(ob.name)it should display bob

如果你尝试console.log(ob.name)它应该显示bob

{}in JS is a shorthand for an object. You can convert your object to string using the toString()method.

{}in JS 是对象的简写。您可以使用该toString()方法将对象转换为字符串。