zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JavaScript之判断参数的数值的详细类型

JavaScript 详细 类型 参数 判断 数值
2023-09-27 14:24:42 时间
//判断是否为字符串
//返回类型:
//{baseType:typeof(arg),numberType:'int','float',-1}
function numberType(arg){
    var baseType;
    var numberType;
    var regx_int =  /^[0-9]*[1-9][0-9]*$/;
    if(!isNaN(arg)){//JavaScript中,属于数值的有:数值型字符串和真实数值       
        baseType = typeof(arg);//输出:string or number
        if(regx_int.test(arg)){//整数
            numberType = "int";
        } else {
            numberType = "float";
        }
    } else {
        baseType = typeof(arg);
        numberType = -1;
    }

    return {
        "arg":arg,
        "baseType": baseType,//注意:typeof(stringNumber):string
        "numberType": numberType
    }
}

/*
    console.log(numberType("23"));  //{arg: "23", baseType: "string", numberType: "int"}
    console.log(numberType("23.0"));//{arg: "23.0", baseType: "string", numberType: "float"}
    console.log(numberType("23a")); //{arg: "23a", baseType: "string", numberType: -1}
    console.log(numberType(23));    //{arg: 23, baseType: "number", numberType: "int"}
    console.log(numberType(23.0));  //{arg: 23, baseType: "number", numberType: "int"}
 */

 

参考文献:

  http://blog.csdn.net/xingfeng0501/article/details/6681912