把数组里的假值转为0

Posted on 2020-09-22 00:31  猫头唔食鱼  阅读(213)  评论(0编辑  收藏  举报
    // 假值转换为0
        let toZero = (arr)=>{
           return arr.map(v=>v||0)
        }
        let c = [1,2,3,0,false,null,undefined,NaN,'']
        console.log(toZero(c)); // [1, 2, 3, 0, 0, 0, 0, 0, 0]

上面这个方法可以把假值,转换为0,但是不能把'0.00','0','0.0000'之类的值转换成为0,因为'0.00','0','0.000'这类的值是真值

所以,如果要把类似'0.00'这样的值转换为0那就要下面的方法

    // 假值转为 0 ,包括'0','0.00','0.0000'和 空字符串,字符串数字转为数字
        let toZero2 = (arr)=>{
            let newArr = []
               arr.forEach(v=>{
                typeof v!=='string'?  ( v = v || 0) :(v =   Number(v) || 0)
                newArr.push(v)
            })
            return newArr
        }
        let d = [1,2,0,'0','0.00','0.0000',undefined,null,false,NaN,3,'','0.03','0.9','100','0.4236']
        console.log(toZero2(d));// [1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0.03, 0.9, 100, 0.4236]

 还可以这样:

 let q = [1,2,0,'0','0.00','0.0000',undefined,null,false,NaN,3,'','0.03','0.9','100','0.4236']
        let toZero3 = (arr)=>{
            let newArr = []
            arr.forEach(v=>{
                typeof v!== 'number'?typeof v === 'string'?(v=+v):(v=0) : !(!!v) && (v=0)
                newArr.push(v)
            })
            return newArr
        }
        console.log(toZero3(q));