javascript 中始终效果不够10位补一个0的效果怎么实现

JavaScript013

javascript 中始终效果不够10位补一个0的效果怎么实现,第1张

下面是我写的一个方法, 应该可以满足你的要求

/**

 * @param num: 需要固定位数的数字或字符串

 * @param totalBit: 保证返回字符串的长度, 默认为10

 * @param isFront: 当num位数不足时, 新填充的字符串是否位于num前面, 默认为true

 * @param fixedChar: 当num位数不足时, 重复填充此字符, 默认为'0'

 * @param alwaysCut: 是否始终保证返回值长度为totalBit, 此值为true时, 如果给定num的长东超过参数中totalBit的大小时, 也会截取totalBit长度的字符串, 默认为false

 * **/

function toFixedBit(num, totalBit, isFront, fixedChar, alwaysCut) {

    if (totalBit === void 0) { totalBit = 10 }

    if (isFront === void 0) { isFront = true }

    if (fixedChar === void 0) { fixedChar = "0" }

    if (alwaysCut === void 0) { alwaysCut = false }

    var nn = num.toString()

    if (!alwaysCut && nn.length >= totalBit) {

        return nn

    }

    var rtn = ""

    for (var i = 0 i < totalBit i++) {

        rtn += fixedChar

    }

    if (isFront) {

        rtn += nn

        rtn = rtn.substr(rtn.length - totalBit)

    }

    else {

        rtn = nn + rtn

        rtn = rtn.substr(0, totalBit)

    }

    return rtn

}

使用方法

console.log(toFixedBit(100)) //输出: 0000000100

console.log(toFixedBit(100, 10, false))//输出: 1000000000

console.log(toFixedBit(100, 10, true, "$", false))//输出: $$$$$$$100

console.log(toFixedBit("aasadfsa4512122", 10, true, "$", true))//输出: fsa4512122

console.log(toFixedBit("aasadfsa4512122", 10, false, "$", true))//输出: aasadfsa45

console.log(toFixedBit("aasadfsa4512122", 10, false, "$", false))//输出: aasadfsa4512122

/**

如此,.slice(-5)表示截取的是从后往前数5位一直到最后

console.log((Array(5).join(0) + 38).slice(-5))// 00038

1)在input失去焦点的func里面操作,

2)检查文本的长度:

if 文本长度离目标长度相差n的话

then input的文本 = n*0 + 原文本

即可。