如何对字符串进行突变? JavaScript

How to make mutation of a string? JavaScript

如果默认情况下对象是可变的,为什么在这种情况下它不起作用? 如何使对象"s"中的键"a"的变异值?

var s = {
  a: "my string"
};

s.a[0] = "9"; // mutation
console.log(s.a); // doesn't work

JavaScript 中的字符串是不可变的。这意味着您不能修改现有字符串,只能创建一个新字符串。

var test = "first string";
test = "new string"; // same variable now refers to a new string

您正在尝试更改原语 String,它在 Javascript 中是不可变的。

例如,如下所示:

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);

应该输出:

myObject.mutation: my other value
myPrimitive.mutation: undefined

但是你可以在原始String的原型中定义一个函数,比如:

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

或者您可以将另一个值分配给 s.a,如 s.a = 'Hello World'

您尝试改变一个不可能的字符串,因为字符串是不可变的。您需要分配新值。

在给定位置更改字母的花式样式下方。

var s = { a: "my string" };

s.a = Object.assign(s.a.split(''), { 0: "9" }).join('');

console.log(s.a);

您正在尝试使用元素访问器改变字符串,这是不可能的。如果您将 'use strict'; 应用于您的脚本,您会看到它出错:

'use strict';

var s = {
  a: "my string"
};

s.a[0] = '9';       // mutation
console.log( s.a ); // doesn't work

如果要替换字符串的字符,则必须使用另一种机制。如果您想看到对象是可变的,只需执行 s.a = '9' 即可,您会看到 a 的值已更改。

'use strict';

var s = {
  a: "my string"
};

s.a = s.a.replace(/./,'9')
console.log(s.a);