473,734 Members | 2,788 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

JavaScript associative arrays not ordered?

Hello everyone.

I am not fluent in JavaScript, so I might overlook the obvious.

But in all other programming languages that I know and that
have associative arrays, or hashes, the elements in the
hash are alphabetically sorted if the key happens to
be alpha numeric. Which I believe makes sense because
it allows for fast lookup of a key.

But in JavaScript, I found this not to be true.

Consider the following function:

function print_assoc_arr ay() {
var assoc_array = new Object();

assoc_array[ "one"] = 1;
assoc_array[ "two"] = 2;
assoc_array["three"] = 3;
assoc_array[ "four"] = 4;
assoc_array[ "five"] = 5;

document.open() ;
for (i in assoc_array) {
document.writel n(i + " = " + assoc_array[i] + "<br>");
}
document.close( );
}

It prints the content of the associative array in insertion
order rather than in alphabetical order (IE6 and FF1.5.0.6).

Am I missing something, or is this expected?
Rene
--
Rene Nyffenegger
http://www.adp-gmbh.ch/
Aug 19 '06 #1
41 4968
Rene Nyffenegger <re************ **@gmx.chwrites :
I am not fluent in JavaScript, so I might overlook the obvious.

But in all other programming languages that I know and that
have associative arrays, or hashes, the elements in the
hash are alphabetically sorted if the key happens to
be alpha numeric.
Well, you know different languages than me. I'm used to Java's
HashMap, which is not sorted at all.
Which I believe makes sense because it allows for fast lookup of a
key.
Only if you depend on the key being sortable, which is a serious
restriction on what you can use as keys.

Implementing an associative array using sorted keys and binary search
makes it expensive to add elements, and still requires logarithmic
time for lookups. Using a hash based implementation has (amortized)
constant time addition and lookup.
But in JavaScript, I found this not to be true.
Nothing requires it to be true. It could be true in some browsers, but
.....
Consider the following function:

function print_assoc_arr ay() {
....
}

It prints the content of the associative array in insertion
order rather than in alphabetical order (IE6 and FF1.5.0.6).
.... that is the traditional behavior of both IE and Netscape, which
other browsers mimic (Opera once tried to ignore it, since remembering
insertion order adds more work to a hash based implementation, but
users demanded that they mimic IE on this)
Am I missing something, or is this expected?
It's expected from tradition. I would prefer that there was no
expectations on the order, since insertion order is pretty arbitrary,
but I guess I'm too late for changing that when there are pages out
there depending on the current behavior.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 19 '06 #2
*** Rene Nyffenegger escribió/wrote (Sat, 19 Aug 2006 08:59:49 +0000
(UTC)):
But in all other programming languages that I know and that
have associative arrays, or hashes, the elements in the
hash are alphabetically sorted if the key happens to
be alpha numeric. Which I believe makes sense because
it allows for fast lookup of a key.
The external representation has nothing to do with the internal
implementation. When you make a directory listing and get files sorted by
name, it doesn't mean that files are physically sorted on disk and OS moves
files around the disk every time you create or rename a file.

In all languages I know (not many, I admit), associative arrays
maintain the insertion order. Which makes sense: otherwise, they wouldn't
be so useful as information storage. Sorting is a resource consuming
operation which cannot be undone. Associative arrays were not created for
performance.

Also, in this exact case, you don't really have an array but an "Object".
JavaScript only defines one-dimension numeric arrays; other sort of arrays
must be simulated with objects. And there's no point in sorting object
attributes alphabetically.
--
-+ http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
++ Mi sitio sobre programación web: http://bits.demogracia.com
+- Mi web de humor con rayos UVA: http://www.demogracia.com
--
Aug 19 '06 #3
Rene Nyffenegger wrote:
I am not fluent in JavaScript, so I might overlook the obvious.

But in all other programming languages that I know and that
have associative arrays, or hashes, the elements in the
hash are alphabetically sorted if the key happens to
be alpha numeric. Which I believe makes sense because
it allows for fast lookup of a key.

But in JavaScript, I found this not to be true.

Consider the following function:

function print_assoc_arr ay() {
var assoc_array = new Object();
assoc_array[ "one"] = 1;
assoc_array[ "two"] = 2;
assoc_array["three"] = 3;
assoc_array[ "four"] = 4;
assoc_array[ "five"] = 5;
document.open() ;
for (i in assoc_array) {
document.writel n(i + " = " + assoc_array[i] + "<br>");
}
document.close( );
}

It prints the content of the associative array in insertion
order rather than in alphabetical order (IE6 and FF1.5.0.6).
I don't know if you can alter the input format; but doing

new numero("one", "1")
new numero("two", "2")
new numero("three", "3")

should leave you all possibilities to sort. See example on:
http://groups.google.com/group/comp....918860bbb62a84

--
Bart

Aug 19 '06 #4
Rene Nyffenegger wrote:
I am not fluent in JavaScript, so I might overlook
the obvious.

But in all other programming languages that I know
and that have associative arrays,
Javascript does not have "associativ e arrays".
or hashes,
Or "hashes".
the elements in the hash are alphabetically sorted
if the key happens to be alpha numeric. Which I
believe makes sense because it allows for fast
lookup of a key.

But in JavaScript, I found this not to be true.

Consider the following function:

function print_assoc_arr ay() {
var assoc_array = new Object();

assoc_array[ "one"] = 1;
assoc_array[ "two"] = 2;
assoc_array["three"] = 3;
assoc_array[ "four"] = 4;
assoc_array[ "five"] = 5;

document.open() ;
for (i in assoc_array) {
The - for-in - statement lists the enumerable properties of an Object
(and its prototype(s)) in an implementation dependent order by
specification (ECMA 262, 3rd Ed. Section 12.6.4). That is, there should
be no expectation of the order.
document.writel n(i + " = " + assoc_array[i] + "<br>");
}
document.close( );
}

It prints the content of the associative array
It is not an "associativ e array" it is a native ECMAScript Object.
in insertion order rather than in alphabetical order
(IE6 and FF1.5.0.6).
Two examples of the same behaviour, where that behaviour is
implementation dependent, are not unexpected but do not guarantee the
same behaviour in other implementations .
Am I missing something,
More likely you are adding something; a miss-association of javascript
Objects with "associativ e arrays" and "hashes" and so the application to
javascript Objects of assumptions about "associativ e arrays" and
"hashes", that will be disappointed as javascript objects are no more
than just that.
or is this expected?
Expected in the sense that actual behaviour satisfies the specified
behaviour.

Richard.
Aug 19 '06 #5
Richard Cornford wrote:
[...]
Javascript does not have "associativ e arrays" [...]
Or "hashes".
[...]
"In JavaScript an object is a mapping from property names to values --
that is, an associative array."

http://en.wikipedia.org/wiki/Associa...ays#JavaScript

--
Bart

Aug 19 '06 #6
On 19/08/2006 13:54, Bart Van der Donck wrote:
Richard Cornford wrote:
>[...]
Javascript does not have "associativ e arrays" [...]
Or "hashes".
[...]

"In JavaScript an object is a mapping from property names to values --
that is, an associative array."

http://en.wikipedia.org/wiki/Associa...ays#JavaScript
Since when has Wikipedia been an authority on the language?

This subject has been covered many times. Search the archives.

Mike
Aug 19 '06 #7
Bart Van der Donck said the following on 8/19/2006 8:54 AM:
Richard Cornford wrote:
>[...]
Javascript does not have "associativ e arrays" [...]
Or "hashes".
[...]

"In JavaScript an object is a mapping from property names to values --
that is, an associative array."

http://en.wikipedia.org/wiki/Associa...ays#JavaScript
Another reason that I do not care for Wikipedia, especially when it is
as wrong as that entry is.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Aug 19 '06 #8
Bart Van der Donck wrote:
Richard Cornford wrote:
>[...]
Javascript does not have "associativ e arrays" [...]
Or "hashes".
[...]

"In JavaScript an object is a mapping from property names
to values -- that is, an associative array."

http://en.wikipedia.org/wiki/Associa...ays#JavaScript
If wikipedia wish to define an "associativ e array" as "a mapping from
property names to values" (or more generally as 'a mapping of keys to
values') then that is their choice. So much of what associative arrays
actually are in practice is disregarded in that definition as to render
it trivial. Under that definition many things become "associativ e
arrays", some of which would be better never to be thought of as
"associativ e arrays".

Dictionary definitions of "array" tend to stress ordering in the
arrangement (and we have heard of the expectation of ordering (in some
sense) in "associativ e arrays" from the OP) yet javascript objects have
no ordering of their properties (except as a coincidental manifestation
of particular object implementations ).

When an "associativ e array" is just created/instantiated in a language
that supports such it would be expected to be empty (or just have the
key/value pairs specified at creation), while the javascript Object is
never 'empty', and so cannot be assumed to not posses a value mapped to
an arbitrary key just because no such key/value pair has been assigned.

Many "associativ e array" in a language that supports such have some
(recoverable) notion of the number of key/value pairs assigned, while
javascript objects have no interest in the number or properties they
contain.

The practice of talking of either javascript Objects or Arrays as
"associativ e arrays" tends to introduce in the minds of the readers who
are familiar with actual associative arrays from other languages an set
of expectations that are not true (or not generally true) of javascript
Objects/Arrays. Inevitably false expectations about javascript will not
be satisfied by javascript, will tend to get in the way of an accurate
understanding of javascript, and will directly result in
issues/problems/bugs in code written to those expectations. The most
reasonable response to this situation is to state clearly that
javascript objects are not "associativ e arrays" and so allow the reader
to move on to the much more productive consideration of what a
javascript Object actually is.

Richard.
Aug 19 '06 #9
Michael Winter wrote:
On 19/08/2006 13:54, Bart Van der Donck wrote:
"In JavaScript an object is a mapping from property names to values --
that is, an associative array."

http://en.wikipedia.org/wiki/Associa...ays#JavaScript

Since when has Wikipedia been an authority on the language?
Maybe the Netscape javascript manual then ? Quote out of
http://wp.netscape.com/eng/mozilla/3...ript/model.htm :

-
myCar["make"] = "Ford"
myCar["model"] = "Mustang"
myCar["year"] = 67
This type of array is known as an associative array, because each
index element is also associated with a string value.
-

--
Bart

Aug 19 '06 #10

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

Similar topics

27
11201
by: Abdullah Kauchali | last post by:
Hi folks, Can one rely on the order of keys inserted into an associative Javascript array? For example: var o = new Object(); o = "Adam"; o = "Eve";
35
6657
by: VK | last post by:
Whatever you wanted to know about it but always were affraid to ask. <http://www.geocities.com/schools_ring/ArrayAndHash.html>
104
16989
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
0
8946
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9310
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6031
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3261
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 we have to send another system
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.