清空JS中的字符串

Empty a String in JS

本文关键字:字符串 JS 清空      更新时间:2024-01-20

如何在JS中清空一个字符串并保持相同的对象引用?

var str= "hello";
str=""; // this will clear the string but will create a new reference 

字符串是不可变的(不可更改的),所以不能这样做。所有"修改"字符串的操作实际上都会创建一个新的/不同的字符串,这样引用就会不同。


您的问题类型通常通过在对象中包含字符串引用来解决。将引用传递给包含对象,然后可以更改字符串,但仍有对新字符串的引用。

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,并使该对象始终包含对字符串最新值的引用。