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
Add a ment  | 

1 Answer 1

Reset to default 9

Strings 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