In JavaScript, the value of a string is immutable, which means that once a string is created, it cannot be changed; reason: the string itself is a basic type encapsulated by the language, and the underlying type is An object whose contents cannot be changed since its creation, so the string remains unchanged.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, the value of a string is immutable, which means that once the string is created, it cannot be changed.
For example, the following code:
var myStr = "Bob"; myStr[0] = "J";
will not change the value of the variable myStr to "Job" because the variable myStr is immutable.
Note that this does not mean that myStr can never be changed, only that the individual characters of the string literal cannot be changed.
The only way to change myStr is to reassign it a value, like this:
var myStr = "Bob"; myStr = "Job";
Why are strings immutable in js?
In fact, the string itself is a basic type encapsulated by the language (output through the system's own String constructor new). The bottom layer is still an object, not a simple data type. The content of this object cannot be changed since it was created, so the string remains unchanged. Operations such as
will only generate new string objects, and the original string objects will not change. If a string object is no longer referenced, it will be recycled by GC.
[Related recommendations: javascript learning tutorial]
The above is the detailed content of Why are strings immutable in javascript?. For more information, please follow other related articles on the PHP Chinese website!