【问题标题】:How do I avoid needing to use parseFloat/Int, number() in the first place with JavaScript?如何避免在 JavaScript 中首先使用 parseFloat/Int, number()?
【发布时间】:2017-06-09 19:11:43
【问题描述】:

当添加一些未引用的对象值时,它有时会连接这些值而不是实际添加它们,因此我使用 parseInt 或 parseFloat 函数围绕这两个值。

例子:

var testobj = 
{

    'test1': 
    {
        'rect': {x:100, y:0, w:0, h:0}
    },

    'line2': 
    {
        'rect': {x:0, y:0, w:200, h:0}
    }

}

var result = parseFloat(testobj['test1'].rect.x) + parseFloat(testObj['test2'].rect.w);

console.log(result); // will give me 300

result = testobj['test1'].rect.x + testObj['test2'].rect.w;

console.log(result); // will give me 100300

我发现我需要使用 parseFloat 真的很烦人。有什么办法可以解决这个问题?

【问题讨论】:

  • 都给我 300 (JsFiddle),你确定这些值没有被引用吗?

标签: javascript parseint parsefloat


【解决方案1】:

如果在变量前面使用+,可以强制变量变为数字,请查看下面的示例。

var testobj = {
    'test1': 
    {
        'rect': {x:'100', y:'0', w:'0', h:'0'}
    },

    'line2': 
    {
        'rect': {x:'0', y:'0', w:'200', h:'0'}
    }
}

var result = +(testobj['test1'].rect.x) + +(testobj['line2'].rect.w);

console.log(result); // will give me 300

result = testobj['test1'].rect.x + testobj['line2'].rect.w;

console.log(result); // will give me 100300

var a = '11';
var b = '22';

var c = '1.25';
var d = '2.25';


console.log('"11" + "22" = ' + a + b);
console.log('+"11" + +"22" = ' + (+a + +b));

console.log(+"11" + +"22");

console.log(c + d);
console.log(+c + +d);

【讨论】:

    【解决方案2】:

    您可以编写一个小函数,将 obj 的所有字符串化的 int/float 键转换为 int/float,因此您在计算时无需反复采取额外措施。

    function parseNumKeys(obj) {
        if( typeof obj == "object" ) {
            for(var key in obj){
                var num = parseFloat(obj[key]);
                isNaN(num)? parseNumKeys(obj[key]) : obj[key] = num; 
            }
        }
    }
    

    将你的 obj 传递给上面的函数:

    var testobj = {
        'test1': 
        {
            'rect': {x:'100', y:'0', w:'0', h:'0'}
        },
    
        'line2': 
        {
            'rect': {x:'0', y:'0', w:'200', h:'0'}
        }
    } 
    
    console.log("before parseNumKeys called: \n", testobj);
    
    parseNumKeys(testobj);
    
    console.log("after parseNumKeys called: \n", testobj);
    
    // before parseNumKeys called: 
    //  { test1: { rect: { x: '100', y: '0', w: '0', h: '0' } },
    //   line2: { rect: { x: '0', y: '0', w: '200', h: '0' } } }
    // after parseNumKeys called: 
    //  { test1: { rect: { x: 100, y: 0, w: 0, h: 0 } },
    //   line2: { rect: {   x: 0, y: 0, w: 200, h: 0 } } }
    

    现在,result = testobj['test1'].rect.x + testobj['line2'].rect.w; 将给出 300 而不是 100300,无需额外处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2016-09-29
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      相关资源
      最近更新 更多