admin管理员组文章数量:1293511
How to empty a string in JS keeping the same object reference ?
var str= "hello";
str=""; // this will clear the string but will create a new reference
How to empty a string in JS keeping the same object reference ?
var str= "hello";
str=""; // this will clear the string but will create a new reference
Share
edited Dec 2, 2013 at 18:47
Felix Kling
817k181 gold badges1.1k silver badges1.2k bronze badges
asked Dec 2, 2013 at 18:45
MokMok
2871 gold badge7 silver badges18 bronze badges
0
1 Answer
Reset to default 9Strings are immutable (unchangable) so you can't do this. All operations that "modify" a string actually create a new/different string so the reference will be different.
Your type of problem is usually solved by having a string reference contained in an object. You pass the reference to the containing object and then you can change the string, but still have a reference to the new string.
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)
This allows code, both before, during and after the myFunc()
function call to change container.myStr
and have that object always contain a reference to the latest value of the string.
本文标签: javascriptEmpty a String in JSStack Overflow
版权声明:本文标题:javascript - Empty a String in JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741581117a2386576.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论