| Step by Step Number
|
luckybutt1987

msg:4375198 | 7:47 pm on Oct 16, 2011 (gmt 0) | hello i am new in javascript. i need a function that works like this.
function my() { var ranNum= [b]some function here that give me step by step number on every call i.e on 1st call to my() it make number 1 and on second call it make number 2. i dont need random.[/b] if (ranNum == 1){ document.write('<p>1</p>'); } if (ranNum == 2){ document.write('<p>2</p>'); } } also one thing more that on the first call must number 1 should generate and on 2nd call must number 2 should generate and after a givin limit its start again from 1 . Please help me i cant figure it out. thank you
|
daveVk

msg:4375284 | 1:57 am on Oct 17, 2011 (gmt 0) | Welcome, something like this. var nextNumber = 1; // initial value function my() { document.write('<p>'+nextNumber+'</p>'); nextNumber++; if ( nextNumber === 11 ) { nextNumber = 1; } }
|
penders

msg:4375360 | 7:47 am on Oct 17, 2011 (gmt 0) | Or, to avoid the use of a global variable you could create a property of the function object itself to emulate a static variable (a variable that is local to the function but holds its value between function calls) - although it's not strictly local since you can read my.ranNum from outside the function. function my() { // Reset if not already defined or greater than some max limit if ((typeof my.ranNum == 'undefined') || (my.ranNum > 1000)) { my.ranNum = 0; } my.ranNum++; document.writeln(my.ranNum); } my(); // 1 my(); // 2 my(); // 3 document.writeln(my.ranNum); // 3 |
| Or, you could use this.ranNum inside the function. Although this creates a global variable - a property of the window object.
|
|
|