Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm assuming that your professor would not be asking you how to reverse a string if he hasn't yet introduced you to the concept of arrays and loops. Basically, a string like <code>John Smith</code> is just an array of characters like this:</p> <pre><code>0123456789 John Smith </code></pre> <p>Again, thinking in the sense that a string is just an array of characters, you have have 10 characters that need to be reversed. So how do you go about doing this? Well, you basically need to take the last character <code>h</code> from the "array" you're given and make it the first character in a new "array" you're going to create. Here's an example:</p> <pre><code>var known = 'John Smith'; var reversed = ''; // I'm making an empty string aka character array var last = known.length - 1 // This is the index of the last character for (var i = 0; i &lt; known.length; i++) { temp += known[last - i]; } </code></pre> <p>(<a href="http://jsfiddle.net/nam6E/" rel="nofollow">You can see it working here</a>)</p> <p>So what's happening?</p> <ul> <li>We're looping over <code>known</code> starting at 0 and ending at 9 (from the first character to the last)</li> <li>During each iteration, <code>i</code> is incrementing from 0 - 9</li> <li><code>last</code> always has a value of 9</li> <li><code>last - i</code> will give us indexes in reverse order (9, 8, 7, ..., 0)</li> <li>So, when <code>i</code> is 0, <code>last - i</code> is 9 and <code>known[9]</code> is "h"; repeat this process and you get the reversed string</li> </ul> <p>Hopefully this helps explain a little better what's happening when you call <code>reverse()</code> on an array.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload