Pooya
Pooya

Reputation: 1012

why does this variable not change?

in this piece of code:

function change(s)
{
  var number = s.replace(/\s+/g, '');
  for(var i = 0; i < number.length ; i++)
  {
    console.log(number[i]); //Line1
    number[i] = '1';
    console.log(number[i]); //Line2
  }
}

the results of Line1 and Line2 are both the same(they return "2") ! what is going on here?!

Upvotes: 4

Views: 146

Answers (3)

saurabh rastogi
saurabh rastogi

Reputation: 11

You are trying to read an string as an array. Char by char. Looks like JS doesn't allow altering value of any index in such case. If you do something like: number = "12345", value at index: (I) will change. That won't solve your purpose though. To do what you are trying to do, you should split the number and then iterate and change.

An example:

function change(s) {
    var number = s.replace(/\s+/g, '');
    var sArr = number.split("");
    for (var i = 0; i < number.length ; i++) {
    console.log(sArr[i]); //Line1 (prints original)
    sArr[i] = i;
    console.log(sArr[i]); //Line2 (prints changed)
    }
    }

Upvotes: 1

dt_slash
dt_slash

Reputation: 57

I can't really tell completely what you want from this, but I think this will do it?

function change(s)
{
    var number = s.replace(/\s+/g, '');
    var newstring = number;
    for(var i = 0; i < number.length ; i++)
    {
        console.log(number[i]); //Line1
        newstring[i] = '1';
        console.log(number[i]); //Line2
    }
    return(newstring); //or something to that effect
}

Now, this is actually kind of pointless code, I assume you're going to be replacing '1' with something a bit more useful.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

Strings in JavaScript are immutable. You can't change them so this line does nothing

number[i] = '1';

Upvotes: 12

Related Questions