if objects are mutable by default why in this case it dosen't work? How to make mutation value of the key "a" in the object "s"?
var s = {
a: "my string"
};
s.a[0] = "9"; // mutation
console.log(s.a); // doesn't work
if objects are mutable by default why in this case it dosen't work? How to make mutation value of the key "a" in the object "s"?
var s = {
a: "my string"
};
s.a[0] = "9"; // mutation
console.log(s.a); // doesn't work
You are trying to change a primitive String
, which is immutable in Javascript.
For exmaple, something like below:
var myObject = new String('my value');
var myPrimitive = 'my value';
function myFunc(x) {
x.mutation = 'my other value';
}
myFunc(myObject);
myFunc(myPrimitive);
console.log('myObject.mutation:', myObject.mutation);
console.log('myPrimitive.mutation:', myPrimitive.mutation);
Should output:
myObject.mutation: my other value
myPrimitive.mutation: undefined
But you can define a function in primitive String's prototype, like:
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
var hello="Hello World"
hello = hello.replaceAt(2, "!!")) //should display He!!o World
Or you can just assign another value to s.a, as s.a = 'Hello World'
Strings in JavaScript are immutable. This means that you cannot modify an existing string, you can only create a new string.
var test = "first string";
test = "new string"; // same variable now refers to a new string
You try to mutate a string which not possible, because strings are immutable. You need an assignment of the new value.
Below a fancy style to change a letter at a given position.
var s = { a: "my string" };
s.a = Object.assign(s.a.split(''), { 0: "9" }).join('');
console.log(s.a);
You are trying to mutate the string using element accessor, which is not possible. If you apply a 'use strict';
to your script, you'll see that it errors out:
'use strict';
var s = {
a: "my string"
};
s.a[0] = '9'; // mutation
console.log( s.a ); // doesn't work
If you want to replace the character of the string, you'll have to use another mechanism. If you want to see that Objects are mutable, simply do s.a = '9'
instead and you'll see the value of a
has been changed.
'use strict';
var s = {
a: "my string"
};
s.a = s.a.replace(/./,'9')
console.log(s.a);