Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Fun with Arrays: What Have I Done?

Reply
Thread Tools

Fun with Arrays: What Have I Done?

 
 
Gene Wirchenko
Guest
Posts: n/a
 
      11-09-2011
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[i]);

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

</script>

</head>

<body>

</body>

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

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

What exactly did I do, please?

Sincerely,

Gene Wirchenko
 
Reply With Quote
 
 
 
 
RobG
Guest
Posts: n/a
 
      11-09-2011
On Nov 9, 2:32 pm, Gene Wirchenko <(E-Mail Removed)> wrote:
> 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[i]);


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[i]);


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
> 1ne
> 2:2
> 3:trois
> 4:undefined
> 5:cinq
> and the second loop outputs
> 0:zero
> 1ne
> 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).

--
Rob
 
Reply With Quote
 
 
 
 
RobG
Guest
Posts: n/a
 
      11-09-2011
On Nov 9, 3:30*pm, RobG <(E-Mail Removed)> wrote:
[...]
> 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.


--
Rob
 
Reply With Quote
 
Tim Streater
Guest
Posts: n/a
 
      11-09-2011
In article <(E-Mail Removed)>,
Gene Wirchenko <(E-Mail Removed)> wrote:

> 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.

--
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted" -- Bill of Rights 1689
 
Reply With Quote
 
SteveYoungTbird
Guest
Posts: n/a
 
      11-09-2011
On 11/09/2011 11:57 AM, Tim Streater wrote:
> In article <(E-Mail Removed)>,
> Gene Wirchenko <(E-Mail Removed)> wrote:
>
>> 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?
 
Reply With Quote
 
Elegie
Guest
Posts: n/a
 
      11-09-2011
On 09/11/2011 11:57, Tim Streater wrote :

Hi Tim,

>> 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 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.


 
Reply With Quote
 
Tim Streater
Guest
Posts: n/a
 
      11-09-2011
In article <4eba62e3$0$681$(E-Mail Removed)>,
Elegie <(E-Mail Removed)> wrote:

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


> >> 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 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.

--
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted" -- Bill of Rights 1689
 
Reply With Quote
 
Gene Wirchenko
Guest
Posts: n/a
 
      11-09-2011
On Wed, 09 Nov 2011 10:57:03 +0000, Tim Streater
<(E-Mail Removed)> wrote:

>In article <(E-Mail Removed)>,
> Gene Wirchenko <(E-Mail Removed)> wrote:
>
>> 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
 
Reply With Quote
 
Dr J R Stockton
Guest
Posts: n/a
 
      11-10-2011
In comp.lang.javascript message <cbd20c37-234b-4bf5-acfc-658d3e5d4811@q3
9g2000prg.googlegroups.com>, Tue, 8 Nov 2011 21:30:00, RobG
<(E-Mail Removed)> posted:

>On Nov 9, 2:32 pm, Gene Wirchenko <(E-Mail Removed)> wrote:


>> 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.


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


--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
Website <http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc. : <http://www.merlyn.demon.co.uk/programs/> - see in 00index.htm
Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
OT Thursday, uh, fun, yeah, fun! Consultant MCSE 17 02-10-2007 03:39 AM
3 PIX VPN questions - FUN FUN FUN frishack@gmail.com Cisco 3 03-16-2006 02:25 PM
OT: Wednesday follow-up-to-Tuesday-Fun Fun Ken Briscoe MCSE 0 07-14-2004 01:41 PM
Programming is not as much fun/more fun than it used to be. Andy Fish Java 65 05-18-2004 08:24 PM
Fun fun fun Luke Computer Support 3 10-07-2003 03:45 PM



Advertisments