Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>undefined</code> is a result of not initializing <code>c_text</code> before you try concatenate it with <code>_x</code>.</p> <p>The code only works on one letter because <code>alphabet.indexOf(x)</code> returns <code>-1</code> (not found). When using <code>o_text = "abc"</code>, <code>x</code> equals 0, 1, and 2. Thus, the index of 0, 1, or 2 in <code>alphabet</code> is nonexistent (indicated by the <code>-1</code> result). You need to relate those numbers back to <code>o_text</code> by changing <code>indexOf(x)</code> to <code>indexOf(o_text[x])</code>. Also, to prevent going outside the bounds of your array, you need a modulus operation to wrap values greater than 26 (I've used <code>alphabet.length</code> to allow this code to work with other alphabets) back around into a valid region. Thus, the correct code would be as follows (note: I've moved 'w' in your array into its proper location alphabetically, as I assumed its location in your example was an error and not intentional):</p> <pre><code>var currentkey = 5 //for example function convertKey(str) { var o_text = str; var o_letters = o_text.split(""); var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] var c_text="", _x = ""; for (x in o_letters) { if (currentkey &gt; 0) { _x = alphabet[(alphabet.indexOf(o_letters[x]) + currentkey) % alphabet.length] } else { _x = alphabet[(alphabet.indexOf(o_letters[x]) + (26 - currentkey)) % alphabet.length] } c_text = c_text + _x; } return c_text; } alert(convertKey('abcdefghijklmnopqrstuvwxyz')); </code></pre> <p>This alert's <code>fghijklmnopqrstuvwxyzabcde</code></p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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