javascript返回单位,如果在乘以2个数字时存在

时间:2016-09-28 21:58:59

标签: javascript

输入到我的函数值的2个数字是a, "0.045u"b, "3"

function mult2nums(a,b) {
    var c = null;
    var unitsFora = null;
    var unitsForb = null;
    var cUnits = null;
    //--> issue - unitsFora = ??; // how to strip off units designator
    //--> issue - unitsForb = ??; // how to strip off units designator
    a = isFloat(a); // also works if int
    b = isFloat(b); //
    c = a*b; 
    // add logic to compare unit designators and convert as needed
    return(c+cUnits); // need to return the units, returns a string type
}

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式过滤单位:

function mult2nums(a,b) {
    var c = null;
    var cUnits = null;
    var unitRegex = /[A-Za-z].*/g
    var unitsForA = a.match(unitRegex);
    var unitsForB = b.match(unitRegex);
    a = parseFloat(a.replace(unitsForA, ''));
    b = parseFloat(b.replace(unitsForB, ''));
    c = a*b; 
    // add logic to compare unit designators and convert as needed
    return c + cUnits;
}

请注意,代码使用第一次遇到的字符作为单位的起始位置。它可以处理大小写差异,以及包含数字的单位(例如m / s ^ 2)。您可以进一步修改代码以满足您的特定需求。

jsFiddle示例: https://jsfiddle.net/ywafx1be/