Why are there two kinds of JavaScript strings?

前端 未结 3 402
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 06:47

This one just stabbed me hard. I don\'t know if it\'s the case with all browsers (I don\'t have any other competent browser to test with), but at least Firefox has two kind

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 07:23

    Another important thing to remember is the following:

    typeof "my-string" // "string"
    typeof String('my-string') // 'string'
    typeof new String("my-string") // "object". 
    

    Therefore, when testing whether an argument or variable is a string you need to do at least the following.

    function isString(arg) {
      if (!arg) {
        return false;
      }
      return typeof arg == "string" || arg.constructor == String;
    }
    

    The above function will still fail if you pass in a String object from another frame/iframe. That is:

    frames[0].myStringVar.constructor != frames[1].myStringVar.constructor
    

    That is because the constructor String is different for each window context. Therefore, a foolproof isString method would be

    function isString(obj) {
       return Object.prototype.toString.call(obj) == "[object String]";
    }
    

提交回复
热议问题