javascript 字符串转换为 undefined/null/number/boolean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18799685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:16:13  来源:igfitidea点击:

String conversion to undefined/null/number/boolean

javascriptnode.js

提问by Gabriel Llamas

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 = function (value){
    if (value === "undefined") return undefined;
    if (value === "null") return null;
    if (value === "true") return true;
    if (value === "false") return false;
    var v = Number (value);
    return isNaN (v) ? value : v;
};


Candidates:

考生:

//Me, Gabriel Llamas
var cast1 = function (value){
    if (value === "undefined") return undefined;
    if (value === "null") return null;
    if (value === "true") return true;
    if (value === "false") return false;
    var v = Number (value);
    return isNaN (v) ? value : v;
};

//KooiInc
var cast2 = function (value){
    var v = Number (value);
    return !isNaN(v) ? v : 
             value === "undefined" ? undefined
         : value === "null" ? null
         : value === "true" ? true
         : value === "false" ? false
         : value
};

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

//Emmissary's proposal
var cast4 = function (value){
    if (value === "undefined") return undefined;
    try{
        return JSON.parse (value);
    }catch (e){
        return value;
    }
};

Benchmark code (using speedy):

基准代码(使用speedy):

var fn = function (cast){
    cast ("undefined");
    cast ("null");
    cast ("true");
    cast ("false");
    cast ("12");
    cast ("12.34");
    cast ("asd");
};

speedy.run ({
    "cast 1": function (){
        fn (cast1);
    },
    "cast 2": function (){
        fn (cast2);
    },
    "cast 3": function (){
        fn (cast3);
    },
    "cast 4": function (){
        fn (cast4);
    }
});

Result:

结果:

File: string-conversion.js

Node v0.10.18
V8 v3.14.5.9
Speedy v0.0.8

Benchmarks: 4
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per benchmark: ~3000ms (3s 0ms)
Total time: ~12000ms (12s 0ms)

Higher is better (ops/sec)

cast 1
  6,270,458 ± 0.2%
cast 2
  3,305,103 ± 0.0%
cast 3
  54,952 ± 0.0%
cast 4
  82,790 ± 0.4%

Elapsed time: 12109ms (12s 109ms)

回答by Niccolò Campolungo

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.

你可以在这里看到jsfiddle

回答by KooiInc

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

这似乎更快@ 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
 }

回答by suffering

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.

动态数据类型转换有很多奇怪的规则,映射一下就行了。