parseInt vs unary plus, when to use which?

后端 未结 5 596
终归单人心
终归单人心 2020-11-22 09:50

What are the differences between this line:

var a = parseInt(\"1\", 10); // a === 1

and this line

var a = +\"1\"; // a ===          


        
5条回答
  •  不要未来只要你来
    2020-11-22 10:19

    The ultimate whatever-to-number conversion table:

    EXPRS = [
        'parseInt(x)',
        'parseFloat(x)',
        'Number(x)',
        '+x',
        '~~x',
        'x>>>0',
        'isNaN(x)'
    
    ];
    
    VALUES = [
        '"123"',
        '"+123"',
        '"-123"',
        '"123.45"',
        '"-123.45"',
        '"12e5"',
        '"12e-5"',
        
        '"0123"',
        '"0000123"',
        '"0b111"',
        '"0o10"',
        '"0xBABE"',
        
        '"4294967295"',
        '"123456789012345678"',
        '"12e999"',
    
        '""',
        '"123foo"',
        '"123.45foo"',
        '"  123   "',
        '"foo"',
        '"12e"',
        '"0b567"',
        '"0o999"',
        '"0xFUZZ"',
    
        '"+0"',
        '"-0"',
        '"Infinity"',
        '"+Infinity"',
        '"-Infinity"',
    
        'null',
        'undefined',
        'true',
        'false',
        'Infinity',
        'NaN',
    
        '{}',
        '{valueOf: function(){return 42}}',
        '{toString: function(){return "56"}}',
    
    ];
    
    //////
    
    function wrap(tag, s) {
        if (s && s.join)
            s = s.join('');
        return '<' + tag + '>' + String(s) + '';
    }
    
    function table(head, rows) {
        return wrap('table', [
            wrap('thead', tr(head)),
            wrap('tbody', rows.map(tr))
        ]);
    }
    
    function tr(row) {
        return wrap('tr', row.map(function (s) {
            return wrap('td', s)
        }));
    }
    
    function val(n) {
        return n === true || Number.isNaN(n) ? wrap('b', n) : String(n);
    }
    
    var rows = VALUES.map(function (v) {
        var x = eval('(' + v + ')');
        return [v].concat(EXPRS.map(function (e) {
            return val(eval(e))
        }));
    });
    
    document.body.innerHTML = table(["x"].concat(EXPRS), rows);
    table { border-collapse: collapse }
    tr:nth-child(odd) { background: #fafafa }
    td { border: 1px solid #e0e0e0; padding: 5px; font: 12px monospace }
    td:not(:first-child) { text-align: right }
    thead td { background: #3663AE; color: white }
    b { color: red }

提交回复
热议问题