473,237 Members | 1,415 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,237 software developers and data experts.

Baffling array problem

I'm a total neophyte in Javascript, trying to hack something together
fast, and run into something that I can't understand at all.

Two loops appear in sequence. The idea is that arrQuestions consists
of the answers to each of 6 questions. Each is answered by a number,
0-5, and each number can only be used once.

So arrNumbers tracks whether a particular number was used as an
answer. arrNumbers[1] would be set to 'Used' if the user answered
"one" on any question.

(All values for arrNumbers are hard-coded to 'Not Used' before this
code runs.)

Loop 1 appears to work. Then I use Loop 2 to loop through arrNumbers
and look for values that are still equal to 'Not Used'. Not only does
this loop fail to work, it actually seems to RESET the values for
arrNumbers!

Am I making some incredibly stupid newbie error here? Have I missed
some fundamental law of JavaScript like you're not allowed to nest an
IF statement within a FOR loop for some damn reason?

I freely admit that I likely don't know what I'm doing, but any and
all help would be greatly appreciated!

for(q = 0; q < 6; q++){
r = arrQuestions[q];
alert(r);
arrNumbers[r]='Used';
alert(arrNumbers[r]);
}

for(s = 0; s < 6; s++){
if(arrNumbers[s]='Not Used'){
alert(s);
alert(arrNumbers[s]);
ArrayOK = false;
}
}
Jun 27 '08 #1
9 1258
On Jun 9, 9:05*pm, djconner <djcon...@gmail.comwrote:
I'm a total neophyte in Javascript, trying to hack something together
fast, and run into something that I can't understand at all.

Two loops appear in sequence. *The idea is that arrQuestions consists
of the answers to each of 6 questions. *Each is answered by a number,
0-5, and each number can only be used once.

So arrNumbers tracks whether a particular number was used as an
answer. *arrNumbers[1] would be set to 'Used' if the user answered
"one" on any question.

(All values for arrNumbers are hard-coded to 'Not Used' before this
code runs.)

Loop 1 appears to work. *Then I use Loop 2 to loop through arrNumbers
and look for values that are still equal to 'Not Used'. *Not only does
this loop fail to work, it actually seems to RESET the values for
arrNumbers!

Am I making some incredibly stupid newbie error here? *Have I missed
some fundamental law of JavaScript like you're not allowed to nest an
IF statement within a FOR loop for some damn reason?

I freely admit that I likely don't know what I'm doing, but any and
all help would be greatly appreciated!

for(q = 0; q < 6; q++){
* * * * r = arrQuestions[q];
* * * * alert(r);
* * * * arrNumbers[r]='Used';
* * * * alert(arrNumbers[r]);

}

for(s = 0; s < 6; s++){
* * * * if(arrNumbers[s]='Not Used'){
* * * * alert(s);
* * * * * * * * alert(arrNumbers[s]);
* * * * * * * * ArrayOK = false;
* * * * }

}- Hide quoted text -

- Show quoted text -
Simple error. Use == instead of = in your if statements - You are
actually setting the variable value with = . The == compares

Bill H
Jun 27 '08 #2
On Jun 10, 11:05 am, djconner <djcon...@gmail.comwrote:
I'm a total neophyte in Javascript, trying to hack something together
fast, and run into something that I can't understand at all.

Two loops appear in sequence. The idea is that arrQuestions consists
of the answers to each of 6 questions. Each is answered by a number,
0-5, and each number can only be used once.

So arrNumbers tracks whether a particular number was used as an
answer. arrNumbers[1] would be set to 'Used' if the user answered
"one" on any question.

(All values for arrNumbers are hard-coded to 'Not Used' before this
code runs.)

Loop 1 appears to work. Then I use Loop 2 to loop through arrNumbers
and look for values that are still equal to 'Not Used'. Not only does
this loop fail to work, it actually seems to RESET the values for
arrNumbers!

Am I making some incredibly stupid newbie error here? Have I missed
some fundamental law of JavaScript like you're not allowed to nest an
IF statement within a FOR loop for some damn reason?

I freely admit that I likely don't know what I'm doing, but any and
all help would be greatly appreciated!

for(q = 0; q < 6; q++){
In addition to what Bill said, initialising variables without the var
keyword makes them global when the code runs. You should keep all
variables local unless you really need them to be global - that is
especially true for counters.

for (var q=0; q<6; q++) {
...
}

You might also consider using a while loop:

var q = 6;
while (q--) {
...
}

r = arrQuestions[q];
alert(r);
arrNumbers[r]='Used';
alert(arrNumbers[r]);

}

for(s = 0; s < 6; s++){
if(arrNumbers[s]='Not Used'){
alert(s);
alert(arrNumbers[s]);
ArrayOK = false;
}

}
A simpler way is to just set the elements of the array when the
question is answered, that way you don't have to initialise the array
with values, e.g.

var arrQuestions = []; // empty array

/* When a question is answered, if the equivalent
** array element evaluates to false (i.e. it's undefined)
*/ the question hasn't been answered so set it to true

if (arrQuestions[i]) {
alert("Already answered");
} else {
arrQuestions[i] = true;
alert("Marked as answered");
}
--
Rob
Jun 27 '08 #3
Thanks everybody, that'll teach me about PWC (Programming While
Clueless!)

On Jun 9, 9:22 pm, RobG <rg...@iinet.net.auwrote:
A simpler way is to just set the elements of the array when the
question is answered, that way you don't have to initialise the array
with values, e.g.
Trouble in this case is that I'm modifying a Frankensteinian creation
that has ASP, HTML, Javascript and VBscript all cobbled together. For
some damned reason just about all the scripting is in VBscript (which
I'm competent with), but the validation code is in Javascript. (An
early lesson for me was that Javascript and VBscript don't play nicely
together....)
Jun 27 '08 #4
On Jun 9, 9:22 pm, RobG <rg...@iinet.net.auwrote:
In addition to what Bill said, initialising variables without the var
keyword makes them global when the code runs. You should keep all
variables local unless you really need them to be global - that is
especially true for counters.

for (var q=0; q<6; q++) {
...
}
I initialized all the counters (with var) at the top of the function,
as I would do in VB - does that work OK?
Jun 27 '08 #5
On Jun 10, 4:46 am, djconner <djcon...@gmail.comwrote:
On Jun 9, 9:22 pm, RobG <rg...@iinet.net.auwrote:
In addition to what Bill said, initialising variables without the var
keyword makes them global when the code runs. You should keep all
variables local unless you really need them to be global - that is
especially true for counters.
for (var q=0; q<6; q++) {
...
}

I initialized all the counters (with var) at the top of the function,
as I would do in VB - does that work OK?
Yes, that is what you want to do in JavaScript.
Jun 27 '08 #6
On Jun 10, 9:46 pm, djconner <djcon...@gmail.comwrote:
On Jun 9, 9:22 pm, RobG <rg...@iinet.net.auwrote:
In addition to what Bill said, initialising variables without the var
keyword makes them global when the code runs. You should keep all
variables local unless you really need them to be global - that is
especially true for counters.
for (var q=0; q<6; q++) {
...
}

I initialized
You mean declared. Initialising is when you declare the variable and
assign a value in one statement, e.g.

var y; // Declared variable
var x = 5; // Number primitive initialiser
var z = []; // Array initialiser

all the counters (with var) at the top of the function,
as I would do in VB - does that work OK?
Since all declarations are processed before any code is executed, you
can actually declare variables anywhere within the intended scope
(function or global). However, most seem to consider it good form to
declare them at the start of the function.

Some like to declare variables at the point they are first used. A
similar scheme is frequently used for loop counters, which are often
declared at the start of the loop, e.g.

for (var i=0, len=array.length; i<len; i--) { ... }

for (var p in obj) { ... }

var j = array.length;
while (j--) { ... }

and so on.

Some recommend against that as it might be interpreted as inferring
block scope (which javascript does not have). I like it because I can
keep track of counters more easily. Nested loops can be written:

for (var i=0, iLen=6; i<iLen; i++) {
for (var j=0, jLen=6; j<jLen; j++) {
...
}
}

so it is clear where it all belongs - but that is just my preference.
--
Rob
Jun 27 '08 #7
djconner wrote:
On Jun 9, 9:22 pm, RobG <rg...@iinet.net.auwrote:
>A simpler way is to just set the elements of the array when the
question is answered, that way you don't have to initialise the array
with values, e.g.

Trouble in this case is that I'm modifying a Frankensteinian creation
that has ASP, HTML, Javascript and VBscript all cobbled together.
This would appear to be the usual way to do it with ASP (server-side
VBScript, client-side J[ava]Script/ECMAScript with fallback), although I
prefer to use server-side JScript instead of server-side VBScript when
having to write for ASP.
For some damned reason just about all the scripting is in VBscript (which
I'm competent with), but the validation code is in Javascript.
The validation code would be scripting, too.
(An early lesson for me was that Javascript and VBscript don't play nicely
together....)
Whatever your problem was, it is not likely to be caused by an
incompatibility of J(ava)Script with VBScript or vice-versa. Chances are
you have been doing something else wrong.

If both J(ava)Script and VBScript are client-side, the former would have to
be JScript because VBScript is not supported by non-MSHTML user agents and
MSHTML-based UAs do not support other ECMAScript implementations than
JScript. In that case, they play nicely together as long as you observe
that they use the same namespace (which can turn to be an advantage,
consider VBScripts versatile MsgBox function for example) and that only one
of them can be the default scripting language unless you use proprietary labels.

If the J(ava)Script code is client-side and the VBScript code is server-side
(or, unlikely, vice-versa), one does not talk directly to the other because
they simply do not know of each other (there are the HTTP client and server
in between). So there is no reason to believe they would not play nicely
together.

If both J(ava)Script and VBScript are server-side in ASP, the former would
have to be JScript, too, because that is what ASP supports. It is
sufficient then to place them in separate script files and use ASP's
<@LANGUAGE@directive to specify the used scripting language in each file.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Jun 27 '08 #8
timothytoe wrote:
>
I understand that a lot of people like to stick the "var" in the for
loop, but I see that as a habit from C that doesn't make as much sense
in JavaScript.
Unlikely, since that was illegal in C until C99, which is still not
widely used.

Perhaps you are thinking of C++, in which the practice of declaring
loop variables in the first clause of the "for" statement is widespread.

--
Michael Wojcik
Micro Focus
Rhetoric & Writing, Michigan State University
Jun 27 '08 #9
In comp.lang.javascript message <b1822aae-7615-4528-9944-c954efd20344@n1
9g2000prg.googlegroups.com>, Wed, 11 Jun 2008 16:29:09, timothytoe
<ti********@gmail.composted:
>On Jun 11, 6:09 am, Dr J R Stockton <j...@merlyn.demon.co.ukwrote:
>In comp.lang.javascript message <0e07a781-089c-45eb-8bf9-81060c19557a@v1
g2000pra.googlegroups.com>, Tue, 10 Jun 2008 13:05:12, timothytoe
<timothy...@gmail.composted:
>I initialized all the counters (with var) at the top of the function,
as I would do in VB - does that work OK?
>Yes, that is what you want to do in JavaScript.

Not really. Variables are commonly declared at the top of their
functions. Counter variables are not commonly initialised there;
instead, they are initialised at the beginning of the loop. I presume
he did, and meant, that.

In the quoted case, that q=0 is the initialisation, independently of
whether the line contains var .
>--
(c) John Stockton, nr London, UK. ?...@merlyn.demon.co.uk Turnpike
v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms,
& links.
Proper <= 4-line sig. separator as above, a line exactly "-- "
(SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or ""
(SonOfRFC1036)


"Counter variables are not commonly initialised there;
instead, they are initialised at the beginning of the loop."

Commonly, perhaps. I follow Crockford's suggestion that all variables
be declared at the top of the function because of how JavaScript is
scoped. I have jslint check for this when I run my code through it. I
expect due to Crockford's book and the popularity of jslint that we'll
see more programmers moving the declaration to the top of functions.

I understand that a lot of people like to stick the "var" in the for
loop, but I see that as a habit from C that doesn't make as much sense
in JavaScript.

Apparently you do not understand the difference between declaration
(which creates a variable) and initialisation (which gives it a value).
Declaration is done with 'var'; initialisation is done with '='.

Please read and heed newsgroup META-FAQ section 2.3.

--
(c) John Stockton, nr London UK. replyYYWW merlyn demon co uk Turnpike 6.05.
Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html-Timo Salmi: Usenet Q&A.
Web <URL:http://www.merlyn.demon.co.uk/news-use.htm: about usage of News.
No Encoding. Quotes precede replies. Snip well. Write clearly. Mail no News.
Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Ben Floyd | last post by:
It goes like this: Im converting a perl script that executes a command on each result of a directory listing. In perl, all is well. In Python, using approximately the same logic creates a...
5
by: TimS | last post by:
I am getting a baffling File not found error (0x800A0035). I am writing asp on a windows 2000 server. I build a path and filename from several fields in a jet database using SQL commands, like...
2
by: paul.driegen | last post by:
Hi all, Hopefully some gurus here can offer some insight into possible causes of this problem..or at least point me in the right direction as to how to solve it. Consider:
2
by: bfrasca | last post by:
I have a well-formed XML file that I am trying to load into a dataset using the ReadXML method. It keeps telling me that "there are multiple root elements". I can view the data using XML Designer...
12
by: Mike | last post by:
I have posted this before, but no one responds, so here it goes again. I think my question is intimidating people and I have no idea why?!? This is not a new concept. You can do this with other...
1
by: Dominic Marks | last post by:
Hello Group, I'm bemused as to why this code isn't working. It's a very simple loop over the array of FileInfo objects returned from DirectoryInfo.GetFiles. It works fine until the eigth...
2
by: Double Echo | last post by:
Hi, Forgive me if I ask a dumb question, I'm new to classes and object programming with PHP, and cannot figure out what the problem is with this class. Maybe I have overlooked something but...
3
by: Scotty | last post by:
I'm a C++ novice and need help figuring out some odd behavior I've encountered. Here's the situation: I create a class and have its constructor store a random number in a private "number"...
1
by: Tim Redfern | last post by:
Hi I'm having an issue that is probably obvious to somebody here but its baffling me.. I'm using python (2.5.1) on an embedded linux sytem system (kernel 2.6.19 I think) with only 32MB memory...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.