如何避免首先使用JavaScript使用parseFloat / Int,number()?

时间:2017-06-09 19:11:44

标签: javascript parseint parsefloat

当添加一些非引用的对象值时,它有时会连接这些值而不是实际添加它们,所以我在这两个值周围使用了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真的很烦人。有办法解决这个问题吗?

2 个答案:

答案 0 :(得分: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);




答案 1 :(得分:1)

你可以编写一个小函数,将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,无需额外处理。