For loops...

G

Gregc.

Hi
I am having trouble understanding for loops. If I have a loop that
says:
var coffee = new Array();
coffee ["mixedblend"] = 5.50;
for (c in coffee)
{code goes here}


That for saying while there is a c in coffee, then conduct the code.
Is that a correct interpretation?


Greg
 
D

Douglas Crockford

Gregc. said:
Hi
I am having trouble understanding for loops. If I have a loop that
says:
var coffee = new Array();
coffee ["mixedblend"] = 5.50;
for (c in coffee)
{code goes here}


That for saying while there is a c in coffee, then conduct the code.
Is that a correct interpretation?

It is good that you asked. First, for this application you should use an Object,
not an Array.

var coffee = {};

It is usually better to use the dot notation. Save the subscript notation for
the cases where dot notation isn't allowed.

coffee.mixedblend = 5.50;

Make sure that the loop variable has been declared locally. You can declare it
in the for statement if you want to.

for (var c in coffee) {

Within the loop, c is the current name, and coffee[c] is the current value. It
is usually a good idea to filter out unwanted stuff that might be in the
inheritance chain.

if (coffee.hasOwnProperty(c)) {

code goes here

}
}

http://javaascript.crockford.com/
 
R

RobG

Gregc. said:
Hi
I am having trouble understanding for loops. If I have a loop that
says:
var coffee = new Array();
coffee ["mixedblend"] = 5.50;

That uses an Array as a plain object, you are not using any of its
special array properties. You could have written:

var coffee = new Object();
coffee ["mixedblend"] = 5.50;

Though the use of an initialiser or object literal is generally
preferred:

var coffee = { mixedblend : 5.50 };

for (c in coffee)
{code goes here}

for (c in coffee ){
alert( coffee[c] );
}

That for saying while there is a c in coffee, then conduct the code.
Is that a correct interpretation?

Almost - change "while there is a c" to "for each enumerable property".

It is usually called a for..in loop to differentiate it from a
conditional for loop. A for..in loop goes over all the enumerable
properties of the object in no particular order (some implementations
will go over them in the order they were added, it is not reliable).
Most built-in objects like the JavaScript Array object have many
non-enumerable properties (e.g. you can't use for..in to get the length
property of an Array).

It is impossible for you to add non-enumerable properties, or to make
the non-enumerable ones enumerable (though you can mask them to give
the appearance of enumerability).
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top