I want to say first. Very beginner. Be kind. However. I am attempting to reverse a string. Put a string into a function as an argument and reverse its order. For example 'hello' should return 'olleh', etc.
I have complete this by doing:
function revString(stringArg) {
return stringArg.split("").reverse().join(");
}
However. By doing it like this:
function revString (stringArg) {
stringArg.split("");
stringArg.reverse();
stringArg.join("");
return stringArg;
}
The resulting output for the second function is that reverse() is not a function. Can someone tell me what the difference here is?
This is because .reverse() is used on the output of .split("").
Using .reverse() by itself doesn't work because the line before it doesn't directly change it unless you reassign it with stringArg = stringArg.split("");. The first line would return the array of characters but doesn't change stringArg directly.
So:
stringArg.split("").reverse().join("");
means to join all elements within the array whose elements are in reverse order based on the spliting of the string. In other words, .reverse() is used on stringArg.split(""), not just stringArg and same with .join(""): it is applied to stringArg.split("").reverse() not just stringArg.
Thus the solution would be:
function revString2 (stringArg) {
a = stringArg.split("");
b = a.reverse();
c = b.join("");
return c;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With