473,465 Members | 1,976 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

for/in loop Array gotcha

I just wanted to let folks know of one more reason not to use for/in
loops on Arrays.

In the following code:

var u = [1,1]
for (var i in u)
print([i, i+2, i-0+2].join());
print(typeof(i) + ' ' + typeof(i-0));

0,02,2
1,12,3
string number

(i+1) does not obtain the expected results because i is a string!
Always use C-like loops when iterating arrays. JavaScript is not
Python!

Ian

Sep 29 '05 #1
15 1887
var u = [1,1]
for (var i in u)
print([i, 2+i, -0+2+parseInt(i)].join());
print(typeof(i) + ' ' + typeof(i-0));

output left for readers to guess

Sep 29 '05 #2
On 29/09/2005 16:49, Ian Osgood wrote:

[snip]
for (var i in u)
[snip]
(i+1) does not obtain the expected results because i is a string!


Of course, because property names are /always/ strings.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Sep 29 '05 #3
"Ian Osgood" <ia**@quirkster.com> writes:
I just wanted to let folks know of one more reason not to use for/in
loops on Arrays.

In the following code:

var u = [1,1]
for (var i in u)
print([i, i+2, i-0+2].join());
print(typeof(i) + ' ' + typeof(i-0));

0,02,2
1,12,3
string number

(i+1) does not obtain the expected results because i is a string!
Always use C-like loops when iterating arrays. JavaScript is not
Python!
Or, you could read the ecmascript spec, in order to find out what the
"for .. in" syntax actually does.

Your "advice" sounds more like a warning than anything else, but I'm
actually glad the "for .. in" syntax exists.

Ian


Arnaud
Sep 30 '05 #4
"aundro" <ad@ionicsoft.nospam.please.com> wrote in message
news:87************@paddy.ionicsoft.com...

[snip]
... I'm actually glad the "for .. in" syntax exists.


I didn't know of it before; thanks.

"The for...in statement is used to iterate a declared variable over every
property in a specified object. The code in the body of the for ... in loop
is executed once for each property."

http://www.devguru.com/Technologies/.../for...in.html
Sep 30 '05 #5
Note also the following odd usage to test for the existence of a
property:-

var a={};
a.myProp=1;

var exists=(myProp in a);

Sep 30 '05 #6
"McKirahan" <Ne**@McKirahan.com> writes:
"aundro" <ad@ionicsoft.nospam.please.com> wrote in message
news:87************@paddy.ionicsoft.com...

[snip]
... I'm actually glad the "for .. in" syntax exists.
I didn't know of it before; thanks.

"The for...in statement is used to iterate a declared variable over every
property in a specified object. The code in the body of the for ... in loop
is executed once for each property."


Ok, here comes a little pedantry:

Some properties won't be iterated over (yet remain accessible) if they
have the 'DontEnum' attribute. How you can reach/set/clear those attributes
however, I absolutely have no idea.. Anybody has any idea?

(see P.65 of http://www.ecma-international.org/pu...s/Ecma-262.htm)

Basically: you don't care about such properties, but heh, it's just
nice to know there can be 'hidden' properties.

http://www.devguru.com/Technologies/.../for...in.html


Arnaud
Sep 30 '05 #7
"Baconbutty" <ju****@baconbutty.com> writes:
Note also the following odd usage to test for the existence of a
property:-

var a={};
a.myProp=1;

var exists=(myProp in a);


Is that proper JS? When I execute in SpiderMonkey:

----8<----
aundro@paddy:~$ js
js> var a={};
js> a.myProp=1;
1
js> var exists=(myProp in a);
3: ReferenceError: myProp is not defined
----8<----

*sob*
Regards,
Arnaud
Sep 30 '05 #8


Baconbutty wrote:
Note also the following odd usage to test for the existence of a
property:-

var a={};
a.myProp=1;

var exists=(myProp in a);


That snippet will give you an error, you need
var exists = "myProp" in a;

There is nothing "odd" about that in my view only that the 'in' operator
is not implemented in older browsers respectively the script engines
they come with, e.g. in Netscape 4 the 'in' operator use will give a
syntax error, the same for IE 5/Mac if I remember a recent discussion
here correctly.
--

Martin Honnen
http://JavaScript.FAQTs.com/
Sep 30 '05 #9

McKirahan wrote:
"aundro" <ad@ionicsoft.nospam.please.com> wrote in message
news:87************@paddy.ionicsoft.com...

[snip]
... I'm actually glad the "for .. in" syntax exists.


I didn't know of it before; thanks.

"The for...in statement is used to iterate a declared variable over every
property in a specified object. The code in the body of the for ... in loop
is executed once for each property."

http://www.devguru.com/Technologies/.../for...in.html


Nice reference. I note that this reference also mentions the use of
for..in on arrays, but without mentioning that the variable comes back
as a string instead of a number.

Ian

Sep 30 '05 #10
>>That snippet will give you an error, you need
var exists = "myProp" in a;


Oops, thank you for that.

Sep 30 '05 #11

aundro wrote:
Some properties won't be iterated over (yet remain accessible) if they
have the 'DontEnum' attribute. How you can reach/set/clear those attributes
however,


Script code itself can't read or set that attribute, it is internal to
an implementation and if you have an application hosting a script engine
then you usually have access to set such attributes on the properties of
the host objects the application creates.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Sep 30 '05 #12
Martin Honnen <ma*******@yahoo.de> writes:
aundro wrote:
Some properties won't be iterated over (yet remain accessible) if they
have the 'DontEnum' attribute. How you can reach/set/clear those attributes
however,
Script code itself can't read or set that attribute, it is internal to
an implementation and if you have an application hosting a script
engine then you usually have access to set such attributes on the
properties of the host objects the application creates.


That's indeed more or less what I was conceiving, but thanks a lot for
the clarification :)

--

Martin Honnen
http://JavaScript.FAQTs.com/

Arnaud

Sep 30 '05 #13
Martin Honnen <ma*******@yahoo.de> writes:

[property attributes like DontEnum]
Script code itself can't read or set that attribute,


Almost correct. There is Object.prototype.propertyIsEnumerable that
allows you to read one of the three attributes (the other two being
ReadOnly and DontDelete, which can't be read, but might be discoverable
by trying to do it and catching the exception :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 30 '05 #14
On 30/09/2005 18:57, Lasse Reichstein Nielsen wrote:

[snip]
(the other two being ReadOnly and DontDelete, which can't be read,
but might be discoverable by trying to do it and catching the
exception :)


No exceptions should be thrown if the delete or assignment operators are
used on DontDelete or ReadOnly properties, respectively. The operation
should silently fail (though the delete operator should evaluate to false).

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Sep 30 '05 #15
chronX
1 New Member
When using prototypes...

As per Brendan Eich's proposal back in 2004(Enumeration of extended properties of Array and Object prototypes), you can use the obj.hasOwnProperty() method to check against inherited properties(prototypes). Yea this means you have to modify your for...in loops here and there, but if you want to use your objects this way then at this point you are going to have to modify your code anyway.

It would be nice to have that DontEnum property available for modding, but until it is, this or a custom Object is your only way around the problem. And from my understanding the for...in shouldn't be used anyway on sparse arrays in the first place. You could look at it like this, if the Object can't evaluate foo.length then for all intents it's not an array so don't use for...in iteration use for...i. Long story short, way too many people are using the wrong iteration constructs in their code.

FYI : about the foo.propertyIsEnumerable() being discussed here, this is taken from 'javascript: The Definitive Guide, 4th Edition', By David Flanagan
ECMAScript specification states that propertyIsEnumerable( ) does not examine the prototype chain, which means that it only works for local properties of an object and does not provide any way to test the enumerability of inherited properties

I am really not sure why this is such a huge issue for everyone, I guess I should say RTFM and pass it along
Feb 20 '06 #16

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

Similar topics

5
by: Blankdraw | last post by:
I can't get this nested loop to break the outer loop at the 5th data value so control can proceed to the next array col and continue pigeon-holing the next 5 in its own column. Why can I not get...
8
by: OZ | last post by:
how to run the index with 1, 2, 2,3,4,5..... in an array from a do loop ? TIA
5
by: John Dumais | last post by:
Hello, I have been trying to figure out how to write an array of doubles (in this specific case) to a binary stream without using a loop. What I have been doing is... foreach(double d in...
15
by: PagCal | last post by:
Is this language missing the functionality of a C/C++ 'continue' statement? For example: While NOT isEof() If condition ' a C or C++ continue would work here ' but we are forced to use a...
24
by: RyanTaylor | last post by:
I have a final coming up later this week in my beginning Java class and my prof has decided to give us possible Javascript code we may have to write. Problem is, we didn't really cover JS and what...
1
by: Mythran | last post by:
How can I set a DefaultValue for an array property? I don't have a project that uses this anymore, but still am curious. Of all the replies I've posted here, a simple thing like this is my...
1
by: Doug_J_W | last post by:
I have a Visual Basic (2005) project that contains around twenty embedded text files as resources. The text files contain two columns of real numbers that are separated by tab deliminator, and are...
6
by: lukasso | last post by:
Hi, this is my code that should produce something like a timetable for a few days with each day divided into 30 minute pieces. It makes query from MySQL and then creates a 2d $array which then is to...
3
by: Magdoll | last post by:
I was trying to map various locations in a file to a dictionary. At first I read through the file using a for-loop, but tell() gave back weird results, so I switched to while, then it worked. ...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.