-1

I don't know why, but this code is not assigning cha[cha.indexOf(x[x.length-1]) + 1]'s value to x[x.length - 1]. I tried to convert it to any array but that didn't do anything.

var cha = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789";
    var n = notch; // number to start counting from
    var x = cha[0];
    // stuff
    console.log(x);
    // generation loop
    while (n > 0) {
        if(x[x.length - 1] == cha[cha.length-1]) {
            // ^ correct logic
            x[length] = cha[0];
        } else {
            // 
            newPush = cha[cha.indexOf(x[x.length-1]) + 1];
            a = x /*.split("");
            a.pop(); <= Failed attempt
            a.push(newPush);*/
            x = a;
            //x[x.length-1] = cha[cha.indexOf(x[x.length-1]) + 1];
            //x[x.length-1] = "D";
            console.log("x[x.length - 1] = " + x[x.length - 1]);
            console.log("cha[cha.indexOf(x[x.length-1]) + 1] = " + cha[cha.indexOf(x[x.length-1]) + 1]);
        }
        n--;
        console.log(cha[cha.indexOf(x[x.length-1]) + 1]);
        console.log(x.lastIndexOf(x[x.length-1]) + 1);

        console.log("n = " + n + ", x = " + x);
    }

I want the new character from cha[cha.indexOf(x[x.length-1]) + 1] assigned to x[x.length - 1]. I've been debugging it in the Chrome developer tools (v23.0.1271.64), but I highly doubt it is specific to Chrome. I probably don't understand the value/reference passing or something, but any help is appreciated. (Please include a code sample if you can.)

  • 2
    `x` starts out as a string of length 1. Why are you trying to treat it like an array? **A string is not an array.** A string is not even mutable. What are you _actually_ trying to accomplish with this code? Moreover, [don't use brackets to index into a string; use `charAt()`](http://stackoverflow.com/q/5943726/139010). – Matt Ball Nov 21 '12 at 19:47
  • @MattBall I understand what you are saying, I've just always done it bracket notation, but I'll try it with charAt(). I am trying to create a string that where `x = "abc"`, the new string will be `"abd"` for example. I just was overwriting `x` for convenience but it could be made a different string. Any way of making a new string this way (example)? – Andrejewski Nov 21 '12 at 20:08
  • Overwriting x: `x = 'abc'; x = x.substring(0, x.length-1) + 'd'` – Matt Ball Nov 21 '12 at 20:20

1 Answers1

0
var alphabet = "abcdefghijklmnopqrstuvwxyz";

prefix = oldString.slice(0, oldString.length - 1);
suffix = oldString.substr(-1, 1);
newSuffix = alphabet.charAt(alphabet.indexOf(suffix) + 1 % alphabet.length);
newString = prefix + newSuffix;
SpacedMonkey
  • 2,725
  • 1
  • 16
  • 17