js如何把一个变量转换成数字类型

Posted on 2019-12-01 18:13  猫头唔食鱼  阅读(4393)  评论(0编辑  收藏  举报

 

     let a = 'a'
        let b =  true 
        let c = NaN
        let d = null
        let e = undefined
        let f = {}
        let g = []
        let h = {name:'zs'}
        let i = ['a']
        let j = '1.03'
        let k = '1.03a'
        let l = 'b1.03a'

 

 // 判断是否NaN
        let isNaN = a => a!=a?true :false

// 把变量转换成数字,不能转换的,就转成NaN
 let toNumber = a =>  {
            if(isNaN(a)){
                return a * 1
            }else{
                if(typeof(a) === 'number'){
                    return parseFloat(a)
                }else{
                    if(typeof(a) === 'string'){
                        return parseFloat(a)
                    }else{
                        return a * 1
                    }
                }
            } 
        }


// 或者
 
        let toNumber2 = a =>  {
            if(isNaN(a)){
                return a - 0
            }else{
                if(typeof(a) === 'number'){
                    return parseFloat(a)
                }else{
                    if(typeof(a) === 'string'){
                        return parseFloat(a)
                    }else{
                        return  a - 0
                    }
                }
            }
        }
 
     console.log(toNumber(a)); // NaN
        console.log(toNumber(b)); // 1 
        console.log(toNumber(c)); // NaN
        console.log(toNumber(d)); // 0
        console.log(toNumber(e)); // NaN
        console.log(toNumber(f)); // NaN
        console.log(toNumber(g)); // 0
        console.log(toNumber(h)); // NaN
        console.log(toNumber(i)); // NaN
        console.log(toNumber(j)); // 1.03
        console.log(toNumber(k)); // 1.03
        console.log(toNumber(l)); // NaN