The example in this article describes the method of JavaScript pre-complement 0 operation. Share to everyone for your reference. Specifically as follows:
Many times in order to display the format, you need to perform a 0 operation in the case of a string with a bit of dissatisfaction.
1. Traditional code
/**
* Front 0 Operation
* @param number string to be manipulated string
* @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 more concise
function Addzero (str,length) {return
new Array (Length-str.length + 1). Join ("0") + str;
}
I hope this article will help you with your JavaScript programming.