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 the same (they return "2")! what's going on here?!

+4
source share
3 answers

Strings in JavaScript are immutable. You cannot change them so that this line does nothing

 number[i] = '1'; 
+12
source

You are trying to read a string as an array. Char to char. It seems that JS does not allow changing the value of any index in this case. If you do something like: number = "12345", the value in the index: (I) will change. However, this will not solve your goal. To do what you are trying to do, you have to divide the number and then iterate over and change.

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) } } 
+1
source

I can’t completely say what you want from this, but I think it 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 really pointless code, I assume that you are going to replace "1" with something more useful.

0
source

Source: https://habr.com/ru/post/1493706/


All Articles