javascript - parseInt vs unary plus,什么时候用哪个?

标签 javascript node.js

这行有什么区别:

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

还有这一行

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

这个 jsperf test表明一元运算符在当前的 chrome 版本中要快得多,假设它是用于 node.js 的!?

如果我尝试转换不是数字的字符串都返回 NaN:

var b = parseInt("test" 10); // b === NaN
var b = +"test"; // b === NaN

那么我什么时候应该更喜欢使用 parseInt 而不是一元加号(尤其是在 node.js 中)???

edit:和双波浪号运算符~~有什么区别?

最佳答案

终极数字转换表: 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"',
    'BigInt(1)',

    '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) + '</' + tag + '>';
}

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) || n === "Error" ? wrap('b', n) : String(n);
}

var rows = VALUES.map(function (v) {
    var x = eval('(' + v + ')');
    return [v].concat(EXPRS.map(function (e) {
        try {
            return val(eval(e));
        } catch {
            return val("Error");
        }
    }));
});

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 }

关于javascript - parseInt vs unary plus,什么时候用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17106681/

相关文章:

javascript - Nodejs 从函数内部调用函数

javascript - 使用带有像素的背景位置的中心图像

javascript - D3 forceX/forceY 和 forceCenter 的区别

javascript - 对 Node 中模块与类的性能影响

javascript - 使用 Node.js 将视频文件流式传输到 html5 视频播放器,以便视频控件继续工作?

javascript - 给定一个 JSON 对象数组,如何根据嵌套值获取 JSON 对象 X?

javascript - 表单中的多个元素转为 JavaScript

javascript - 如何使用 AngularJS $q 延迟 promise 从异步函数返回数据?

javascript - 为什么js类不使用public和private关键字?

node.js - 单个 SHOULD 查询 block 中的多个条件