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?
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?
Share Improve this question edited Feb 16, 2017 at 17:04 atsang01 asked Feb 16, 2017 at 16:48 atsang01atsang01 2274 silver badges14 bronze badges 4-
why don't you just return the
result
variable in yourconsole.log()
? – Nicolas Commented Feb 16, 2017 at 16:49 -
2
I don't understand.
console.log
will just print whatever value you pass it to the console. That same value is still available. Could you please create a MCVE to show us your problem? – Mike Cluck Commented Feb 16, 2017 at 16:49 - Do you want to convert result to a string? Then JSON.stringify is your friend: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Patrick Hund Commented Feb 16, 2017 at 16:51
-
As @PatrickHund said, if you are logging and array and you want to get the string of the array you should consider using
JSON.stringify()
but once again, this question lack a lot of information. – Nicolas Commented Feb 16, 2017 at 16:53
1 Answer
Reset to default 3console.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 ments 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);