如何在JS中清空一个字符串,保持相同的对象引用?
var str= "hello"; str=""; // this will clear the string but will create a new reference
jfriend00.. 8
字符串是不可变的(不可变),所以你不能这样做."修改"字符串的所有操作实际上都会创建一个新的/不同的字符串,因此引用将是不同的.
您的问题类型通常通过在对象中包含字符串引用来解决.您将引用传递给包含对象,然后您可以更改字符串,但仍然引用新字符串.
var container = { myStr: "hello"; }; container.myStr = ""; myFunc(container); // myFunc could have modified container.myStr and the new value would be here console.log(container.myStr)
这允许myFunc()
函数调用之前,期间和之后的代码更改container.myStr
并使该对象始终包含对字符串的最新值的引用.
字符串是不可变的(不可变),所以你不能这样做."修改"字符串的所有操作实际上都会创建一个新的/不同的字符串,因此引用将是不同的.
您的问题类型通常通过在对象中包含字符串引用来解决.您将引用传递给包含对象,然后您可以更改字符串,但仍然引用新字符串.
var container = { myStr: "hello"; }; container.myStr = ""; myFunc(container); // myFunc could have modified container.myStr and the new value would be here console.log(container.myStr)
这允许myFunc()
函数调用之前,期间和之后的代码更改container.myStr
并使该对象始终包含对字符串的最新值的引用.