473,761 Members | 2,410 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
41 4974
Michael Winter wrote:
>>[MW] Since when has Wikipedia been an authority on the language?
[BVdD] Maybe the Netscape javascript manual then ?
[MW] That still wouldn't automatically eliminate the misuse of terminology.
Sun ?
http://java.sun.com/javascript/ajaxi...ction_ApB.html

"The JavaScript object is essentially just an associative array,
with fields and methods keyed by name."

Microsoft ?
http://msdn.microsoft.com/msdnmag/is...3/03/XMLFiles/

"If you need to pass in complex types [...] you can use associative
arrays in JavaScript."
> 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.

That's a worse description: myCar need not be an array (none of this has
/anything/ to do with arrays), and, in reference to "index element",
those strings are not indices; they are property names.
This smells like language fetishism - indices or keys are common names
to describe this kind of referencing. Doesn't matter how it's
implemented internally, it's the general working that is being
described here.
Again, I ask you to read the archives. Unless you have something new to
add, there's no point repeating this debate. I can't say that I'd look
forward to a ninth discussion of this subject.
I did read the archives, and, as you probably know, it's a
controversial subject. But if Wikipedia, Netscape, Microsoft, Sun (and
probably more) all mention associative arrays in such clear terms, I
find the "official" comp.lang.javas cript point of view very
questionable.

--
Bart

Aug 23 '06 #21
Bart Van der Donck wrote:
Michael Winter wrote:
<snip>
I did read the archives, and, as you probably know, it's a
controversial subject. But if Wikipedia, Netscape, Microsoft, Sun
(and probably more) all mention associative arrays in such clear
terms, I find the "official" comp.lang.javas cript point of view very
questionable.
Because it makes perfect sense to follow the people who cause the
problem and disregard the people who have to deal with the
consequences. It remains the case that if you say "associativ e array"
you are likely introduce expectations that are not satisfied in
javascript. Inexpert authors may not know enough to appreciate that,
and so propagate their inadequacies in documents they write. The
consequences are negative and so the usage should be discouraged.

Richard.

Aug 23 '06 #22
Richard Cornford wrote:
Bart Van der Donck wrote:
>[...] But if Wikipedia, Netscape, Microsoft, Sun
(and probably more) all mention associative arrays in such clear
terms, I find the "official" comp.lang.javas cript point of view very
questionable .

Because it makes perfect sense to follow the people who cause the
problem and disregard the people who have to deal with the
consequences. It remains the case that if you say "associativ e array"
you are likely introduce expectations that are not satisfied in
javascript. Inexpert authors may not know enough to appreciate that,
and so propagate their inadequacies in documents they write. The
consequences are negative and so the usage should be discouraged.
I think you're missing the point. I'm not saying anything at all on how
associative arrays work/behave in javascript. A programmer must be
aware of language-specific particularities , yes, but that's only a
technical thing, not a fundamental or conceptual thing.

Those language-specific implementations don't really matter too; it is
the general principle that matters.

"Associativ e array" is not a "directly harmful term", as you claimed in
another post. They are an idea, a description, something that
programmers recognize, a general accepted type of variable. It's also
meant to behave that way in javascript; their syntax, lookup and
overall working are close to what you find in most other computer
languages. Even if there are things that are not possible in
javascript, doesn't mean that they are not associative arrays anymore.

Is a car without a roof not a car ? You say: "It's not a car, but a
cabrio". The second part of that statement is true, but you can't
extrapolate that fact to justify the first part. This kind of thinking
is intellectually unfair; of course it's a cabrio, but that doesn't
mean that it's not a car.

Another analogy: Is a car on electricity not a car ? Sure it is. It's
the general accepted idea of a car that matters here, not whether they
drive on fuel or gas or electricity.

--
Bart

Aug 23 '06 #23
Bart Van der Donck wrote:
Richard Cornford wrote:
>Bart Van der Donck wrote:
>>[...] But if Wikipedia, Netscape, Microsoft, Sun
(and probably more) all mention associative arrays in such clear
terms, I find the "official" comp.lang.javas cript point of view very
questionabl e.

Because it makes perfect sense to follow the people who cause the
problem and disregard the people who have to deal with the
consequences . It remains the case that if you say "associativ e array"
you are likely introduce expectations that are not satisfied in
javascript. Inexpert authors may not know enough to appreciate that,
and so propagate their inadequacies in documents they write. The
consequences are negative and so the usage should be discouraged.

I think you're missing the point. I'm not saying anything at all on
how associative arrays work/behave in javascript.
As javascript has no associative arrays they don't.
A programmer must be aware of language-specific
particularities , yes, but that's only a technical thing,
not a fundamental or conceptual thing.
You have avoided rising to the challenge of stating a detention of an
associative array that includes all the things that are associative
arrays and javascript objects. A simple definition of an associative
array might be; a thing in which values may be stored using arbitrary
key, from which that value may then be retrieved using the same key,
and with which the use of a key that has never been used to store a
value will not retrieve a value.

That definition is fairly close to the concept of an associative array,
but a javascript object does not qualify.

If you can state a viable definition of an associative array that does
not disqualify the javascript object, includes all the things that are
associative arrays and does not include things that self-evidently are
not associative arrays then there might be some reason for changing my
position. As it stands the fact that you cannot use arbitrary keys with
javascript objects (by specification) precludes their classification as
associative arrays (and suggests that anyone who wants to categorise
them as such is actually just unaware of the issues).
Those language-specific implementations don't really matter too;
it is the general principle that matters.
But the general principle is - arbitrary key == value.
"Associativ e array" is not a "directly harmful term", as you
claimed in another post.
Yes, a harmful term when applied to a javascript object.
They are an idea, a description, something that
programmers recognize, a general accepted type of variable.
Precisely. The term brings expectations and javascript does not satisfy
those expectations. The bugs that follow from the resulting
misconception are non-obvious, often only occurring infrequently and
unexpected, making them hard to find, if noticed at all. The result of
trying to carry an inappropriate expectation into javascript is that
the javascript authoring is worse.
It's also meant to behave that way in javascript;
Not if they don't exist in javascript.
their syntax, lookup and overall working are close to what
you find in most other computer languages.
Really? How many associative array implementations will not let you
store a value using an arbitrary key? How many will return a value that
was never stored? How many will return a value that differs from the
one stored? How many will not let you remove a key value pair that you
have previously stored.
Even if there are things that are not possible in
javascript, doesn't mean that they are not associative
arrays anymore.
How many things have to not be possible before something is not an
associative array? Is, for example, a Java Array and associative array
because you may safely use a limited set of non-arbitrary keys to store
and retrieve values of a pre-determined type? How about the Java
Vector; the same restriction to non-arbitrary keys but more flexibility
in what may be stored?
Is a car without a roof not a car ? You say: "It's not a car,
but a cabrio".
No, I would say that is a car, but I would say that the similarities
between a railway engine and a care (wheels, engine, doors, driver's
seat) are not sufficient to categorise one as a car.
Another analogy: Is a car on electricity not a car ? Sure it is. It's
the general accepted idea of a car that matters here, not whether
they drive on fuel or gas or electricity.
And if the general concept of an associative array is that arbitrary
keys may be safely used to store and retrieve values then a javascript
object does not qualify.

Richard.

Aug 23 '06 #24
Richard Cornford wrote:
And if the general concept of an associative array is that arbitrary
keys may be safely used to store and retrieve values then a javascript
object does not qualify.
How "arbitrary" must keys be in order to qualify as an associative array?
In Java since I can't use null as a key in a HashTable, is that not
arbitrary enough and therefore not an associative array?

IMO, the more accurate and easily understood explanation for javascript is
that it has associative arrays by using an Object(), but that there are some
"reserved words" which should not be used as keys. As long as you don't use
those keys, the Object() works exactly like an associative array that most
programmers on the planet would recognize.

I'd suggest that instead of the experts here constantly telling posters
"there are no associative arrays in js!" just to argue a technicality, a
more helpful response might be:

In javascript, an Object() can be used as an "associativ e array" to store
key/value pairs. However, since the Object in javascript has properties
(which translate into keys) by default, special care needs to be taken to
avoid naming collisions with these keys and retrieving values for keys which
were never explicitly set. So, if you want to guarantee that you won't have
problems and want to truly use arbitrary keys, this object will work:

function HashTable() { ... }

Now, wouldn't that be more helpful?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 23 '06 #25
"Matt Kruse" <ne********@mat tkruse.comwrite s:
Richard Cornford wrote:
>And if the general concept of an associative array is that arbitrary
keys may be safely used to store and retrieve values then a javascript
object does not qualify.

How "arbitrary" must keys be in order to qualify as an associative array?
In Java since I can't use null as a key in a HashTable, is that not
arbitrary enough and therefore not an associative array?
Excuse my swooping in, but Java's HashTable accepts much more "arbitrary"
keys than JavaScript's Object.

In JavaScript, you can use strings only as key. Numbers, booleans,
will translate to a string when used as a key, and that will cause no
problem, but what happens when you use an Object as key? All objects
will be translated to the same string (in SpiderMonkey, it is the
string "[object Object]", I'm not sure about other implementations ).

So, you cannot use two different objects as two distinct keys, as they
will all translate to the same string.

Regards,

Arnaud.
[deletia]
Aug 23 '06 #26
Matt Kruse wrote:
Richard Cornford wrote:
And if the general concept of an associative array is that arbitrary
keys may be safely used to store and retrieve values then a javascript
object does not qualify.

How "arbitrary" must keys be in order to qualify as an associative
array?
As the keys that must be used in javascript are all strings then
sufficiently arbitrarily will be any sequence of characters.
In Java since I can't use null as a key in a HashTable, is that not
arbitrary enough and therefore not an associative array?
The difference between using anything except null and anything
including null is minimal, but is a HashTable an associative array or a
hash table?

I still think that the question of whether a javascript Object is an
associative array would be best approached by defining what is meant by
an associative array, and coming up with a definition that includes all
the things that can be agreed to be associative arrays but excludes
thing that are obviously not associative arrays (such as the Java
Vector). With that demarcation it should be easy to see that javascript
objects are not associative arrays. I would not be too concerned about
what such a definition made of Java's HashTable or HashMap objects as
they could be argued either way.
IMO, the more accurate and easily understood explanation for
javascript is that it has associative arrays by using an Object(),
but that there are some "reserved words"
It is things like that that leave me having no regard for your opinion.
"Reserved word" has an absolutely precise meaning.
which should not be used as keys. As long as you don't use
those keys,
So people will be fine if they do not use reserved words like "this",
"do", "default", "null" and "class" as object property names? That
would be total nonsense as none of those names are likely to provoke
any issues. These are the type of misunderstandin g that can follow from
the imprecise use of terminology.
the Object() works exactly like an associative array that
most programmers on the planet would recognize.
If that were true why do so many programmers question the fact that the
length properties of arrays no reflect the number of properties added
to an array, or that Object objects do not have a length property by
default? These questions follow from it being suggested to them that
javascript objects can be treated as associative arrays, when they have
expectations about what an associative array is.
I'd suggest that instead of the experts here constantly telling
posters "there are no associative arrays in js!" just to argue
a technicality, a more helpful response might be:
It is not arguing a technicality; it is saying "take all those
pre-conceptions you have about associative arrays and throw them out"
as they don't apply to javascript objects.
In javascript, an Object() can be used as an "associativ e array" to
store key/value pairs.
Why, when you could say in javascript an Object can have named
properties added to it and removed from it at runtime, and values
assigned to those properties?
However, since the Object in javascript has properties
(which translate into keys) by default, special care needs to be taken to
avoid naming collisions with these keys and retrieving values for keys which
were never explicitly set.
So, if you want to guarantee that you won't have problems
and want to truly use arbitrary keys, this object will work:
Would you like to have another go at that sentence, as it reads
differently each time I try, and none of them makes sense?
function HashTable() { ... }

Now, wouldn't that be more helpful?
In what sense?

Richard.

Aug 23 '06 #27
Arnaud Diederen aundro wrote:
"Matt Kruse" <ne********@mat tkruse.comwrite s:
>Richard Cornford wrote:
<snip>
In JavaScript, you can use strings only as key.
Property names are only strings in the sense of being sequences of zero
or more characters. If a property of an object is accessed as:-

var val = obj.somePropert y;

- the - someProperty - is not a string (in the sense of being a
javascript string primitive or String Object), it is an Identifier.

The sense in which property names are strings is only that in a bracket
notation property accessor any expression inside the brackets is
type-converted into a string before the resulting is used to look up
the property on the object.
Numbers, booleans, will translate to a string when used as a
key, and that will cause no problem, but what happens when
you use an Object as key?
An object reference is type-converted into a string primitive. If the
object has a - toString - method then that is used (with the resulting
value being type-converted to a string if it is not one) else if the
object has a - valueOf - method that is used (with the resulting value
being type-converted to a string if it is not one (which is more
expected)), and if the object does not have either method an exception
is thrown.
All objects will be translated to the same string (in
SpiderMonkey, it is the string "[object Object]",
The - toStirng - method inherited from - Object.prototyp e - returns
that value. If the toString methods is overloaded all sorts of
alternative values could be returned.
I'm not sure about other implementations ).
They vary.
So, you cannot use two different objects as two distinct keys, as
they will all translate to the same string.
You can effectively use object references in the brackets of bracket
notation property accessors so long as they have overloaded - toString
- methods that return suitably object-instance unique string values
that are consistent over time.

Generally that isn't done though.

Richard.

Aug 23 '06 #28
"Richard Cornford" <Ri*****@litote s.demon.co.ukwr ites:
>Numbers, booleans, will translate to a string when used as a
key, and that will cause no problem, but what happens when
you use an Object as key?

An object reference is type-converted into a string primitive. If the
object has a - toString - method then that is used (with the resulting
value being type-converted to a string if it is not one) else if the
object has a - valueOf - method that is used (with the resulting value
being type-converted to a string if it is not one (which is more
expected)), and if the object does not have either method an exception
is thrown.
>All objects will be translated to the same string (in
SpiderMonkey , it is the string "[object Object]",

The - toStirng - method inherited from - Object.prototyp e - returns
that value. If the toString methods is overloaded all sorts of
alternative values could be returned.
>I'm not sure about other implementations ).

They vary.
>So, you cannot use two different objects as two distinct keys, as
they will all translate to the same string.

You can effectively use object references in the brackets of bracket
notation property accessors so long as they have overloaded - toString
- methods that return suitably object-instance unique string values
that are consistent over time.

Generally that isn't done though.
Yes, that's why I kinda forgot about the fact that "[object Object]"
is simply the result of the default toString() method available on
Object.prototyp e.

Your whole explanation puts some pieces back into place. Thank you!

Arnaud.
>
Richard.
--
Arnaud DIEDEREN
Software Developer
IONIC Software
Rue de Wallonie, 18 - 4460 Grace-Hollogne - Belgium
Tel: +32.4.3640364 - Fax: +32.4.2534737
mailto:ad@ionic soft.com
http://www.ionicsoft.com
Aug 23 '06 #29
Bart Van der Donck wrote:
Michael Winter wrote:
>>>[MW] Since when has Wikipedia been an authority on the language?
[BVdD] Maybe the Netscape javascript manual then ?
[MW] That still wouldn't automatically eliminate the misuse of terminology.

Sun ?
http://java.sun.com/javascript/ajaxi...ction_ApB.html

"The JavaScript object is essentially just an associative array,
with fields and methods keyed by name."
The phrase "is essentially" indicates a simplification, not an
equivalence, and that would be fine if a more accurate explanation
occurred later. Unfortunately, that doesn't happen.

By the way, Richard, it seems that Jim was given the credits in that
book for the closures article in the FAQ notes, not you. It seems quite
shocking that the authors can misread: "Written by Richard Cornford."
I am not opposed to the use of terms that may ease a programmer from one
language into another, but when /only/ those terms are used to provide
an explanation, it leaves room for confusion and the creation of
misconceptions. How many times have you seen script authors write:

var map = new Array();

map['key'] = 'value';

as though any of the array-like syntax actually means anything? That is,
when:

var map = {}; // or: new Object();

map.key = 'value';

or:

var map = {
key : 'value'
};

would do just as well. I've seen it a lot, and it stems from the
misunderstandin g of the nature of objects in ECMAScript. It isn't
difficult to accept that objects can have dynamically-assigned
properties; one doesn't need to turn to concepts in other languages to
describe that feature.

[snip]
>That's a worse description: myCar need not be an array (none of
this has /anything/ to do with arrays), and, in reference to "index
element", those strings are not indices; they are property names.

This smells like language fetishism - indices or keys are common
names to describe this kind of referencing.
When used in the right context, yes. However, as the object in question
wasn't an associative array, the terms don't apply.
Doesn't matter how it's implemented internally, ...
At what point in this thread have I mentioned internal implementations ?

[snip]
I did read the archives, and, as you probably know, it's a
controversial subject.
Given that I've read all of the discussions on the subject from the past
three years or so, and participated in several of them, yes, I'm aware.
But if Wikipedia, Netscape, Microsoft, Sun (and probably more) all
mention associative arrays in such clear terms, I find the "official"
comp.lang.javas cript point of view very questionable.
Evidentially, but that seems to be because you fail to recognise, or
refuse to acknowledge, the consequences of describing the language in a
potentially misleading way.

If there was a clear benefit to using the term, or if it really did
apply, I could understand your persistence in this matter. As things
stand, though, I do not.

Mike
Aug 23 '06 #30

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

Similar topics

27
11206
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
6666
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
17002
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
9538
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
9353
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10123
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
6623
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
5241
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5384
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3889
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
3
3481
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2765
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.