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