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

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

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

10条回答
  •  深忆病人
    2020-11-22 03:48

    The string type value is immutable, but the String object, which is created by using the String() constructor, is mutable, because it is an object and you can add new properties to it.

    > var str = new String("test")
    undefined
    > str
    [String: 'test']
    > str.newProp = "some value"
    'some value'
    > str
    { [String: 'test'] newProp: 'some value' }
    

    Meanwhile, although you can add new properties, you can't change the already existing properties

    A screenshot of a test in Chrome console

    In conclusion, 1. all string type value (primitive type) is immutable. 2. The String object is mutable, but the string type value (primitive type) it contains is immutable.

提交回复
热议问题