Fun with Arrays: What Have I Done?


G

Gene Wirchenko

Dear JavaScripters:

I do not remember where I got the idea that JavaScript can handle
arrays with string indexes, but I decided to try it, because it could
simplify certain code that I am planning.

In the course of my experiments -- KRA-KOOM! -- I came up with
the following code. I appear to have two slightly different arrays
with some elements in common or one array with an alter ego. Could
someone please explain why?

***** Start of Code *****
<html>

<!--
try3.html
Array Playaround
Last Modification: 2011-11-08
-->

<head>
<title>try3.html: Array Playaround</title>

<script type="text/javascript">

var Collection=new Array(3);
Collection[0]="zero";
Collection[1]="one";
Collection[2]=2;
Collection[3]="trois";
Collection["seven"]=8-1;
Collection[5]="cinq";

for (var i=0; i<Collection.length; i++)
alert(i+":"+Collection);

for (i in Collection)
alert(i+":"+Collection);

</script>

</head>

<body>

</body>

</html>
***** End of Code *****

The first loop outputs
0:zero
1:eek:ne
2:2
3:trois
4:undefined
5:cinq
and the second loop outputs
0:zero
1:eek:ne
2:2
3:trois
5:cinq
seven:7

What exactly did I do, please?

Sincerely,

Gene Wirchenko
 
Ad

Advertisements

R

RobG

Dear JavaScripters:

I do not remember where I got the idea that JavaScript can handle
arrays with string indexes, but I decided to try it, because it could
simplify certain code that I am planning.

In javascript, arrays are just objects with a special length property
and some handy inherited methods. Otherwise, they are just like
objects in that they are collections of name/value pairs, where the
names are strings.

In the course of my experiments -- KRA-KOOM! -- I came up with
the following code. I appear to have two slightly different arrays
with some elements in common or one array with an alter ego. Could
someone please explain why?

***** Start of Code *****
<html>

<!--
try3.html
Array Playaround
Last Modification: 2011-11-08
-->

<head>
<title>try3.html: Array Playaround</title>

<script type="text/javascript">

var Collection=new Array(3);

That creates an array with a length of 3. Variables starting with a
capital letter are normally (by convention) reserved for constructors.
Setting the length is usually unnecessary, the array can be
initialised with:

var collection = [];

Collection[0]="zero";

Even though a number has been used to create the property, it is
converted to a string to create a property named '0' and the value
'zero' is assigned.
Collection[1]="one";
Collection[2]=2;
Collection[3]="trois";
Collection["seven"]=8-1;
Collection[5]="cinq";

The length property is always one greater than the largest positive
integer index, so the length is now 6. You could have initialised the
array as:

var collection = ['zero', 'one', 2, 'trois',,''cinq'];
collection.seven = 8 - 1;

Note that dot notation can be used for property access where the name
follows the rules for valid identifiers, square bracket notation can
be used for that and where the name isn't a valid identifier (e.g.
it's a number).

Also note the use of an elision between 'trois' and 'cinq'. It
increases the length for that position but does not create a property
'4' (well, at least not in browsers that conform to ECMA-262).
for (var i=0; i<Collection.length; i++)
alert(i+":"+Collection);


That uses an index to visit the properties named 0, 1, 2 etc. up to 5
(converting numbers to strings for use as property names). Since there
is no property for '4', collection[4] returns undefined. Also, it will
not return any properties that aren't named 0 to 5 inclusive.
for (i in Collection)
alert(i+":"+Collection);


That will iterate over the enumerable properties of the array in an
implementation dependent order. Since there is no property named '4',
it will not be returned and since there is a property named 'seven',
it will. For..in will also return enumerable properties on the
prototype chain, so be careful of that.

[...]
***** End of Code *****

The first loop outputs
0:zero
1:eek:ne
2:2
3:trois
4:undefined
5:cinq
and the second loop outputs
0:zero
1:eek:ne
2:2
3:trois
5:cinq
seven:7

What exactly did I do, please?

Hopefully I've explained that above. Try it in various browsers and
you'll see a difference in order returned by for..in (e.g. try it in
IE 8, which returns the properties in the order they were added).
 
R

RobG

The length property is always one greater than the largest positive
integer index

That should be "... is always *at least* one greater ..." since the
length can be set to any positive integer number (within the limits of
0 to 2^32 - 1).

Setting length higher than the highest index just increases the value
of 'length', it doesn't create any extra properties. Setting it
shorter truncates the array so the highest index is now one less than
length and any elements with names equal to or greater than length are
discarded.

See ECMA-262 § 15.4.
 
T

Tim Streater

Gene Wirchenko said:
Dear JavaScripters:
[snip]

What exactly did I do, please?

What you did was not to get a book on JavaScript and read up about
arrays and objects.
 
S

SteveYoungTbird

Gene Wirchenko said:
Dear JavaScripters:
[snip]

What exactly did I do, please?

What you did was not to get a book on JavaScript and read up about
arrays and objects.

That's what he didn't do, not what he did!

Anyway, aren't people allowed to ask questions here any more?
 
E

Elegie

On 09/11/2011 11:57, Tim Streater wrote :

Hi Tim,
What you did was not to get a book on JavaScript and read up about
arrays and objects.

I don't really have a problem with that. The OP is a beginner, yet he
did try out some things with arrays, before posting a clear case (which
elicited an excellent answer by RobG).

Imagine you try and learn Java. You start working with arrays, hear
about lists, mix in generics, and a few test cases later you get strange
issues. You post these, and the reply you get is "Don't bother us,
invariance and covariance of entities are trivial stuff, RTFM". How do
you feel?

Don't get me wrong, reading books or specifications are definitely
necessary steps to becoming a proficient programmer. However, I believe
that the learning process is a progressive thing, and that you should
not try to read all of them before interacting with other people. Not
only you would not know if what you read is what should be read, you
would not understand how the things you learn articulate together, and
you would probably end building (slowly and painfully) a wrong
representation of the technology (unless you're really bright).

Just my 2c, YMMV.

Kind regards,
Elegie.
 
Ad

Advertisements

T

Tim Streater

Elegie said:
On 09/11/2011 11:57, Tim Streater wrote :

I don't really have a problem with that. The OP is a beginner, yet he
did try out some things with arrays, before posting a clear case (which
elicited an excellent answer by RobG).

Oh indeed, and that's the best way to go: try things out and see what
happens. All I'm saying is that the next step after that is to read your
books and see if your observations make sense in the context of the
book's content. A well-written book (as opposed to simply the language
spec) will help the reader create a mental picture of what's going on.
Imagine you try and learn Java. You start working with arrays, hear
about lists, mix in generics, and a few test cases later you get strange
issues. You post these, and the reply you get is "Don't bother us,
invariance and covariance of entities are trivial stuff, RTFM". How do
you feel?

Well annoyed obviously, if I *have* RTFM, and still have holes in my
mental picture. Worst case in my personal experience was when I had an
HTML table that was rendering funny. In alt.html all I got was the usual
BS and people picking up on trivial matters (in the way that PointyHead
does). Eventually someone with a bit more brains suggested adding a
DOCTYPE to get my browser out of quirks mode, which solved my problem.

In that instance, I'd probably read about quirks mode or DOCTYPEs in my
books, but hadn't appreciated their significance. *That* is the point at
which ng's come in to their own.

So I don't think the OP shouldn't be asking questions, but it may be
quicker to poke around the web first.
 
G

Gene Wirchenko

Gene Wirchenko said:
Dear JavaScripters:
[snip]

What exactly did I do, please?

What you did was not to get a book on JavaScript and read up about
arrays and objects.

I did. Unfortunately, the text does not cover some things. One
tends to find out this when one tries looking something up. I did
some Web searches to find out about string indexes for arrays. That
did not completely cover it either though. I experimented and got
some results which I wrote up.

I would like to understand. That is why I asked.

I am also very familiar with the phenomonen of missing something
and having it pointed out casually by someone else. I would rather
ask than slam myself into a wall.

Sincerely,

Gene Wirchenko
 
Ad

Advertisements

D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
9g2000prg.googlegroups.com>, Tue, 8 Nov 2011 21:30:00, RobG

As an experienced programmer (IIRC), you /should/ have got it from
reading ECMA 262 version 5.1 section 15.4 paragraph 1, if not before.
The standard is not suitable for novice programmers; but an experienced
programmer, reading its words once through, should spot quite a few odd
things in the language which it might be worth knowing the existence of.

Unfortunately, there are many regions of the standard which are
comparatively easy to understand.

The length property is always one greater than the largest positive
the largest non-negative, I think.
integer index, so the length is now 6.
and [].length = 0
 

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

Top