Here is what I use (tested too)
function padIt (a,b) {c=a+""; while(c.length < b) {c="0"+c;} return c;}
for those not Prontoscript fluent:
c=a+""; causes c to be converted to a string in case 'a' was an integer and is necessary for the while test to work correctly as an integer has an undefined length. If a was already a string then concatenating it with an empty string does nothing
In Javascript the Plus(+) operator is overloaded and takes on two different operations; addition and concatenation. The overloading is resolved by the context in which the operator is used. This can run into unexpected issues when one wants to build a string that terminates in an integer number. For example
label="Item_";
System.print(label); produces "Item_"
label="Item_"+1;
System.print(label); produces "Item_1"
label="Item_"+1+2;
System.print(label); produces "Item_12"
label="Item_"+(1+2);
System.print(label); produces "Item_3"
The (1+2) causes that term to be evaluted arithmetically since the "(" starts a new context. In the case "Item_"+1+2 the evaluation proceeds from left to right with the left side providing the context. Ergo evaluating "Item_"+1 causes "1" to be converted to a string and then concatenated to "Item_" yielding "Item_1".
The two most bothersome attributes of Javascript (to me) are the fact that symbols are case sensitive and the overloading of "+". I was trained on languages where symbols are case insensitive. Most of my semantic errors in Javascript code I write are due to the symbols being case sensitive in Javascript; since most syntax checkers will not catch that
Last edited by Barry Gordon on October 5, 2010 20:36.