String conversion to undefined/null/number/boolean

后端 未结 3 2078
梦毁少年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: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.

提交回复
热议问题