简体   繁体   中英

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? I am having trouble returning the result of 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. Why is that?

console.log formats whatever you pass inside to a string and outputs it. You can do the same, by explicitly calling toString() as follows:

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:

return JSON.stringify(result, null, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM