简体   繁体   English

Javascript:如何将console.log结果返回为字符串形式?

[英]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.

相关问题 如何在javascript代码中获取console.log的结果字符串? - How to get result string of console.log in javascript code? 如何存储计算器的结果并返回 alert 或 console.log? - How can I store the result of a calculator and return with alert or console.log? 如何让 console.log 输出 getter 结果而不是字符串“[Getter/Setter]”? - How can I get console.log to output the getter result instead of the string "[Getter/Setter]"? 我如何在console.log中如何发送#form值? - how can i console.log how the #form values will be sent? Vuejs:如何 console.log() 所有表单输入? - Vuejs : How can I console.log() all form inputs? JavaScript:如何使这个 console.log() 工作? - JavaScript: How can I make this console.log() work? 为什么当我尝试重复指定次数的字符串时Javascript console.log结果为NaN - Why Javascript console.log result is NaN when I tried Repeat a string a specified times 如何显示 console.log? - How can I display console.log? javascript 中返回的 function 字符串,如何直接从 console.log 中打印一条消息? - How to add a printed message from console.log directly into the return function string in javascript? 如何将两个表单输入值获取到 Javascript console.log - How to get two form input values to Javascript console.log
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM