function to generalize

J

John

Hi,

Would appreciate any help in in generalizing the following so that one
can input from a form any number one wishes.

var s;
var t;
var u;
var v;
var w;
var x;
var y;
var z;

var out = "";

function count() {

for (s=0; s<2; s++) {
for (t=0; t<2; t++) {
for (u=0; u<2; u++) {
for (v=0; v<2; v++) {
for (w=0; w<2; w++) {
for (x=0; x<2; x++) {
for (y=0; y<2; y++) {
for (z=0; z<2; z++) {



var tot =z*1+y*2+x*4+w*8+v*16+u*32+t*64+s*128;


out = out + "\n " + tot;
}
}
}
}
}
}
}
}

window.document.myform.value = out;

}


Thanks.
 
R

Richard Cornford

John said:
Would appreciate any help in in generalizing the following
so that one can input from a form any number one wishes.

Are you serious? This function does nothing more than output (well,
almost) the numbers 0 to 255 inclusive, a totally trivial action
implemented with one of the most convoluted, inefficient and perverse
methods possible.

In fact the code is so wrong, while still exhibiting a knowledge of, for
example, binary, that I find it difficult to see how it could be
anything other than deliberately perverse. Possibly a tutor written
starting point for an early exercise in some sort of programming course.
If so posting the <= 5 line function that would output a count from zero
to any numeric parameter would defeat the exercise. Instead you should
refer to your textbooks, specifically look at the action of the - for -
loop (hint - you only need one). To complete the task it would also be a
good idea to recognise the difference between global variables and
function local variables, look at function return statements and passing
arguments to functions and understand JavaScript's only number type.

window.document.myform.value = out;
<snip>

Forms do not have value properties. You should be writing to the value
property of a form element, probably an <input type="text"> or
<textarea> filed, something like (for example):-

document.forms["aForm"].elements["resultField"].value = whatever;

-with-

<form name="aForm" action="">
...
<textarea cols="60" rows="30" name="resultField"></textarea>
...
</form>

But a generalised function would not directly assign its result to a
named field in a named form, it would just return the string and allow
specific code to do the assignment.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top