JavaScript before zeroing operation instance

  • 2020-05-12 02:14:48
  • OfStack

This article illustrates the method of zero - padding before JavaScript. Share with you for your reference. The details are as follows:

Most of the time in order to display the format, you need to do a pre-padding of 0 if a 1 string is less than a bit long.

1. Traditional code


/**
 *  before 0 operation 
 * @param number String  Pending string 
 * @param length int  The length of the target 
 */
function addZero(number, length) {
  var buffer = "";
  if (number == "") {
    for (var i = 0; i < length; i ++) {
      buffer += "0";
    }
  } else {
    if (length < number.length) {
      return "";
    } else if (length == number.length) {
      return number;
    } else {
      for (var i = 0; i < (length - number.length); i ++) {
        buffer += "0";
      }
      buffer += number;
    }
  }
  return buffer;
}

2. This code is more concise


function addZero(str,length){        
  return new Array(length - str.length + 1).join("0") + str;
}

I hope this article is helpful for you to design javascript program.


Related articles: