Is String a Primitive type or Object in Javascript?

前端 未结 4 1015
栀梦
栀梦 2020-11-30 04:55

Is String a Primitive type or Object in Javascript? Source says Undefined, Null, Boolean, Number and String are all primitive types in Javascript. But it says String is an O

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 05:09

    Both.

    There is a String object and there are string literals.

    You can call any string method on a literal and you can call any string method on a string object.

    The major difference is that a string object generates a new object so new String("foo") !== new String("foo")

    That and a String object is type "object" and not "string"

    How to check for both?

    if(typeof(s) == "string" || s instanceof String){
      //s is a string (literal or object)
    }
    

    Credits to @Triynko for the snippet in the comments

提交回复
热议问题