Are JavaScript strings immutable? Do I need a “string builder” in JavaScript?

后端 未结 10 2419
挽巷
挽巷 2020-11-22 02:48

Does javascript use immutable or mutable strings? Do I need a \"string builder\"?

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 03:39

    It's a late post, but I didn't find a good book quote among the answers.

    Here's a definite except from a reliable book:

    Strings are immutable in ECMAScript, meaning that once they are created, their values cannot change. To change the string held by a variable, the original string must be destroyed and the variable filled with another string containing a new value... —Professional JavaScript for Web Developers, 3rd Ed., p.43

    Now, the answer which quotes Rhino book's excerpt is right about string immutability but wrong saying "Strings are assigned by reference, not by value." (probably they originally meant to put the words an opposite way).

    The "reference/value" misconception is clarified in the "Professional JavaScript", chapter named "Primitive and Reference values":

    The five primitive types...[are]: Undefined, Null, Boolean, Number, and String. These variables are said to be accessed by value, because you are manipulating the actual value stored in the variable. —Professional JavaScript for Web Developers, 3rd Ed., p.85

    that's opposed to objects:

    When you manipulate an object, you’re really working on a reference to that object rather than the actual object itself. For this reason, such values are said to be accessed by reference.—Professional JavaScript for Web Developers, 3rd Ed., p.85

提交回复
热议问题