Why wont this javascript function work?

Red Squirrel

No Lifer
May 24, 2003
67,385
12,131
126
www.anyf.ca
Code:
function lzero(str, len) 
{
  str += ''; // cast to string
  
  while(str.length < len)
  {
	  str = "0".str;
  }
  
  return str;
}

When the value of str passed to the function is 0 to 9, I get the error "TypeError: str is undefined" for the while loop. Why is this?

I just want to add leading zeros to a number. Is there maybe a better way?
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,250
3,845
75
You appear to be confusing your concatenation operators. The string "0" does not have a property "str".
 

Red Squirrel

No Lifer
May 24, 2003
67,385
12,131
126
www.anyf.ca
Oh so it thinks I want to access a property? How do I force it to actually concatenate? Figured the quotes would do as variables don't have quotes. Also the odd part is that I got this off the internet, and most examples I find are similar, and none work.

edit:

OHHHHh it's + and not . I was being confused, and guess the first example I found was wrong or maybe was for php (said javascript though). I got it now, thanks. Never even thought the issue was after the error.
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
PHP = .
javacript = +

... which can be confusing if you're working with both languages at the same time :)