JavaScript string of stubborn

About stubborn JavaScript string: may not be modified

We string
our slogan is: you may destroy me, but you can not change me

JavaScript strings are immutable, it is really so?

Let's try it.

var name = "Coder-Monkey"
console.log(name[0])     // C
console.log(name[11])    // y

These results suggest that a string can be accessed by index.

Try to change it:

name[0] = "X"
name[11] = "X"
console.log(name)       // Coder-Monkey

Really have backbone, change does not move.

  • JS, the constant value as a fixed character string stored in the stack
  • Value of the string can not be changed by the subscript

Can not change this, it seems beyond the imagination of many people, usually experience shows that when the coding can change ah. .

In fact, it is not changed, but it re-assignment, pointing to the memory address of another string is located.

Like this is possible:

name = "CoderMonkie"
console.log(name)       // CoderMonkie

Then, when the need to "modify" the original string, rather than re-assigned a value irrelevant how to do it?

See usage scenarios, if the clear content before and after modification, may be a string replacereplacement method.

If so, just modify the specified location as in the example in the beginning, then we can modify to simulate the operation around a circle.

  • Strings by split('')a method string to an array
  • Modify the array by array subscript
  • Through the array join('')and then the array is connected to a string method

Above, is completed.

Talk is cheep, so show you the code.

var arr = name.split('')
arr[0] = 'X'
arr[11] = 'X'
name = arr.join('')

console.log(name)
// XoderMonkiX

Guess you like

Origin www.cnblogs.com/CoderMonkie/p/cannot-modify-string-in-js.html