[英]string.replace replaces reference string
i have a text replacing function below, 我在下面有一个文本替换功能,
function msgConstructor(type, language, withUserName, userName) {
var txtAndPayloadType = {}
switch (language) {
case Enums.DeviceLanguages.tr:
txtAndPayloadType = Dictionary.tr.notifications[type]
break;
case Enums.DeviceLanguages.en:
default:
txtAndPayloadType = Dictionary.en.notifications[type]
break;
}
txtAndPayloadType.text = txtAndPayloadType.text.replace('[userName]', userName).replace('[withUserName]', withUserName)
return txtAndPayloadType;
}
I am getting the value from Dictionary to a seperate var but somehow .replace call on it's text effects the value in Dictionary. 我从字典中获取值到一个单独的var,但是以某种方式对它的文本进行.replace调用会影响字典中的值。 I think this has something to do with prototype level. 我认为这与原型级别有关。 How can i really copy the value from Dictionary to a new var? 我怎样才能真正地将值从Dictionary复制到新的var?
When you create an object like so: 当您像这样创建一个对象时:
var a = { a: 1 };
var b = a;
a
only references b
. a
仅引用b
。 No matter if you then change a property in a
or b
, it's the same object you're updating. 不管你再更改属性a
或b
,这是您要更新的同一个对象。
b.a = 2;
console.log(a.a); // Outputs 2
console.log(b.a); // Outputs 2
console.log(a === b); // Outputs true
It doesn't work like this for strings: 对于字符串,它不像这样工作:
var a = "a";
var b = a;
b = "b";
console.log(a); // Outputs "a"
console.log(b); // Outputs "b"
console.log(a === b); // Outputs false
What you could do, is only copy the text
property, which contains a string: 您可以做的只是复制text
属性,该属性包含一个字符串:
var newText;
switch (language) {
case Enums.DeviceLanguages.tr:
newText = Dictionary.tr.notifications[type].text;
break;
case Enums.DeviceLanguages.en:
default:
newText = Dictionary.en.notifications[type].text;
break;
}
return {
text: newText
.replace('[userName]', userName)
.replace('[withUserName]', withUserName)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.