[英]Javascript: How can I return console.log result into string form?
As title, I am getting the result that I wanted from console.log(result), however, how can I pass this console.log result to the string variable and "return" it? 作为标题,我从console.log(result)中获得了想要的结果,但是,如何将这个console.log结果传递给字符串变量并“返回”呢? I am having trouble returning the result of console.log().
我无法返回console.log()的结果。 Thanks!
谢谢!
var type = ["men","women","boys", "girls"]
var product = "women shoes";
product.split(' ').forEach(function(item){
type.forEach(function(elem){
if(elem==item){
console.log(elem);
}
});
});
Thank you for all the answers here, and it is so amazing that so many people are willing to help my beginner problem. 感谢您在此提供的所有答案,这真是太神奇了,以至于很多人愿意帮助我解决初学者的问题。 Let me clear my question a little bit here, like above, console.log (elem) will return woman, however, if i replace the line concole.log(elem) with return(elem) will get me nothing.
让我在这里稍微澄清一下我的问题,像上面一样,console.log(elem)会返回女人,但是,如果我用return(elem)替换concole.log(elem)行将不会给我任何帮助。 Why is that?
这是为什么?
console.log
formats whatever you pass inside to a string and outputs it. console.log
会将您传递给字符串的所有内容格式化并输出。 You can do the same, by explicitly calling toString()
as follows: 您可以通过显式调用
toString()
来执行相同的操作,如下所示:
console.log(result);
return result.toString();
As mentioned in the comments by @Patrick Hund, if result is a Javascript object, you can use JSON.stringify
to convert it to a string (and then return it) as follows: 如@Patrick Hund在评论中所述,如果result是一个Javascript对象,则可以使用
JSON.stringify
将其转换为字符串(然后返回),如下所示:
return JSON.stringify(result, null, 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.