This article describes the method of pre-zero operation of JavaScript. Share it for your reference. The details are as follows:
In order to display the format, it is necessary to perform the first 0 operation if a certain string does not meet the bit.
1. Traditional code
/** * Before the operation* @param number String String to be operated* @param length int Target length*/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 simpler
function addZero(str,length){ return new Array(length - str.length + 1).join("0") + str;}I hope this article will be helpful to everyone's JavaScript programming.