简体   繁体   English

如何使字符串变异? JavaScript的

[英]How to make mutation of a string? JavaScript

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"? 如何在对象“s”中创建关键字“a”的变异值?

 var s = { a: "my string" }; sa[0] = "9"; // mutation console.log(sa); // doesn't work 

Strings in JavaScript are immutable. JavaScript中的字符串是不可变的。 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 are trying to change a string in javascript which is immutable. 您正在尝试更改javascript中不可变的字符串。

If you want to change the string. 如果要更改字符串。 You need to define a function in its prototype chain as 您需要在其原型链中定义一个函数

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 as, as as = 'Hello World' 或者您可以将另一个值分配给as, as = 'Hello World'

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" }; sa = Object.assign(sasplit(''), { 0: "9" }).join(''); console.log(sa); 

You are trying to mutate the string using element accessor, which is not possible. 您正在尝试使用元素访问器变异字符串,这是不可能的。 If you apply a 'use strict'; 如果你申请'use strict'; to your script, you'll see that it errors out: 到你的脚本,你会看到它错误:

 'use strict'; var s = { a: "my string" }; sa[0] = '9'; // mutation console.log( sa ); // 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 sa = '9' instead and you'll see the value of a has been changed. 如果你想看到的对象是可变的,根本就sa = '9'来代替,你会看到的价值a已经改变。

 'use strict'; var s = { a: "my string" }; sa = sareplace(/./,'9') console.log(sa); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM