Reputation: 1160
If I chain it: reverser.split(" ").reverse().split(" "), it works. But, if I split, reverse, then join the variable -- it doesn't perform the join:
var s = "How are you";
function reverser(str){
var reversed = str.split(" ");
reversed.reverse();
reversed.join(" ");
return reversed;
};
console.log("does not work", reverser(s));
console.log("works", reverser(s).join(" "));
Upvotes: 1
Views: 1664
Reputation: 1676
split() splits the string into array of strings. You need to store the resulting output everytime so that next operation can be performed right.
var s = "How are you";
function reverser(str){
var reverser = str.split(" ");
var revArray=reverser.reverse();
var revArrayJoined=revArray.join(" ");
return revArrayJoined;
};
console.log(reverser(s));
//output: you are How
Upvotes: 1
Reputation: 12478
joins returns a string and you have to store it in the variable.
var s = "How are you";
function reverser(str){
var reversed = str.split(" ");
reversed.reverse();
reversed=reversed.join(" ");
return reversed;
};
console.log('doesn\'t work ', reverser(s));
Upvotes: 2
Reputation: 413757
The .join()
function returns a string. It doesn't transform the target array into a string.
So,
reverser = reverser.join(" ");
Upvotes: 2