String conversion to undefined/null/number/boolean

后端 未结 3 2044
梦毁少年i
梦毁少年i 2021-01-02 11:23

Do you know any better and faster way to convert a string to the type it represents?

I\'ve always been using this function:

var convertType = functio         


        
相关标签:
3条回答
  • 2021-01-02 12:12

    How about:

    var convertType = function (value){
      var values = {undefined: undefined, null: null, true: true, false: false}
         ,isNumber = !isNaN(+(value));
      return isNumber && +(value) || !(value in values) && value || values[value];
    };
    convertType('null');      //=> null
    convertType('something'); //=> "something"
    convertType('57.321');    //=> 57.321
    convertType('undefined'); //=> undefined
    

    This seems faster @ jsPerf

    var convertType = function (value){
        var v = Number (value);
        return !isNaN(v) ? v : 
             value === "undefined" ? undefined
           : value === "null" ? null
           : value === "true" ? true
           : value === "false" ? false
           : value
     }
    
    0 讨论(0)
  • 2021-01-02 12:23

    This is a simple function which involves the use of a function to evaluate the strings. This way you can remove the part of cases' "switch". Be aware that this handles also assignments to global variables, so I recommend it only if you know anytime where is the source from(don't allow users to use this function!)

    var convertType = function (value){
        try {
            return (new Function("return " + value + ";"))();
        } catch(e) {
            return value;
        }
    };
    

    You can see the jsfiddle here.

    0 讨论(0)
  • 2021-01-02 12:29
    var string2literal = function (value){
      var maps = {
       "NaN": NaN,
       "null": null,
       "undefined": undefined,
       "Infinity": Infinity,
       "-Infinity": -Infinity
       }
      return ((value in maps) ? maps[value] : value);
    };
    

    There are many weird rules in dynamic data type converting, just map it.

    0 讨论(0)
提交回复
热议问题