By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,666 Members | 1,924 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,666 IT Pros & Developers. It's quick & easy.

JavaScript associative arrays not ordered?

P: n/a
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_array() {
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.writeln(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
Share this Question
Share on Google+
41 Replies


P: n/a
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_array() {
....
}

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/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 19 '06 #2

P: n/a
*** 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

P: n/a
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_array() {
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.writeln(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

P: n/a
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 "associative 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_array() {
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.writeln(i + " = " + assoc_array[i] + "<br>");
}
document.close();
}

It prints the content of the associative array
It is not an "associative 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 "associative arrays" and "hashes" and so the application to
javascript Objects of assumptions about "associative 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

P: n/a
Richard Cornford wrote:
[...]
Javascript does not have "associative 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

P: n/a
On 19/08/2006 13:54, Bart Van der Donck wrote:
Richard Cornford wrote:
>[...]
Javascript does not have "associative 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

P: n/a
Bart Van der Donck said the following on 8/19/2006 8:54 AM:
Richard Cornford wrote:
>[...]
Javascript does not have "associative 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.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Aug 19 '06 #8

P: n/a
Bart Van der Donck wrote:
Richard Cornford wrote:
>[...]
Javascript does not have "associative 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 "associative 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 "associative
arrays", some of which would be better never to be thought of as
"associative 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 "associative arrays" from the OP) yet javascript objects have
no ordering of their properties (except as a coincidental manifestation
of particular object implementations).

When an "associative 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 "associative 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
"associative 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 "associative 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

P: n/a
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

P: n/a
Richard Cornford wrote:
[...]
If wikipedia wish to define an "associative 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 "associative
arrays", some of which would be better never to be thought of as
"associative 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 "associative arrays" from the OP) yet javascript objects have
no ordering of their properties (except as a coincidental manifestation
of particular object implementations).

When an "associative 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 "associative 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
"associative 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 "associative arrays" and so allow the reader
to move on to the much more productive consideration of what a
javascript Object actually is.
You're extremely precise and strictly analytic in describing the
behaviour of "associative arrays" in javascript; but one can also look
at them from a more conceptual point of view.

"associative arrays" have different finetunings in various computer
languages, but that doesn't mean that the overall idea isn't the same.
There are German cars and French cars, but both are cars; though they
might not always work the same. I think this kind of view is the most
honest one; I'm even leaving in the middle whether or not a term
"associative array" is justified in javascript.

But it's pretty safe to assume that the principle of "associative
arrays" is present in javascript, albeit with some (minor)
particularities, which you rightly pointed out.

But almost any language has such specific points:
http://en.wikipedia.org/wiki/Associa...nguage_support
And that doesn't mean that the principle of "associative arrays" isn't
the same across those languages. If declaration, assignment, key/value,
representation, syntactical appearance, look-up methodology and general
working of such variables all correspond to the computer-scientific
idea of "associative arrays", then I would vote to name them as such in
javascript too.

--
Bart

Aug 19 '06 #11

P: n/a
Rene Nyffenegger wrote:
I am not fluent in JavaScript, so I might overlook the obvious.
That right there is the source of a lot of misunderstanding about JavaScript. It
is different from other languages in some profound ways. If you insist on
thinking about it as though it were a different language, you will not use it
correctly.

There is no substitute for knowing what you are doing.
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.
It depends on the underlying data structure. Something like a B-tree sorts.
Something like a hashtable, which has faster retrieval characteristics, does
not. The ECMAScript standard does not dictate the underlying data structure.
But in JavaScript, I found this not to be true.

Consider the following function:

function print_object() {
var i, o = {};

o[ "one"] = 1;
o[ "two"] = 2;
o["three"] = 3;
o[ "four"] = 4;
o[ "five"] = 5;
document.writeln('<pre>');
for (i in o) {
document.writeln(i + " = " + o[i]);
}
document.writeln('<\/pre>');
}

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?
Most implementations of ECMAScript tend to return items in insertion order. The
standard does not guarantee /any/ particular order. You should not assume any.

http://javascript.crockford.com/
Aug 19 '06 #12

P: n/a
On 19/08/2006 15:42, Bart Van der Donck wrote:
Michael Winter wrote:
[snip]
>Since when has Wikipedia been an authority on the language?

Maybe the Netscape javascript manual then ?
That still wouldn't automatically eliminate the misuse of terminology.
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.

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.

Mike
Aug 19 '06 #13

P: n/a
Bart Van der Donck wrote:
Richard Cornford wrote:
>[...]
If wikipedia wish to define an "associative 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
"associative arrays", some of which would be better never to be
thought of as "associative 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 "associative arrays" from the OP) yet javascript
objects have no ordering of their properties (except as a
coincidental manifestation of particular object implementations).

When an "associative 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 "associative 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
"associative 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 "associative arrays"
and so allow the reader to move on to the much more productive
consideration of what a javascript Object actually is.

You're extremely precise and strictly analytic in describing
the behaviour of "associative arrays" in javascript;
If you cannot be precise about a programming language what could you be
precise about?
but one can also look
at them from a more conceptual point of view.
And you can also look at them from a more miss-conceptual point of view.
"associative arrays" have different finetunings in various
computer languages, but that doesn't mean that the overall
idea isn't the same.
Which overall idea?
There are German cars and French cars, but both are cars;
though they might not always work the same. I think this
kind of view is the most honest one; I'm even leaving in
the middle whether or not a term "associative array" is
justified in javascript.
The term is directly harmful when associated with javascript's native
Objects/Arrays.
But it's pretty safe to assume that the principle of
"associative arrays" is present in javascript,
This is a 'principle of associative arrays"' in which it is not possible
to use arbitrary string keys to store values within an associative
array, not possible to use arbitrary string keys to retrieve a stored
value (as a consequence of not being able to store values under all
possible keys) and from which arbitrary string keys cannot necessarily
be removed?
albeit with some (minor) particularities,
which you rightly pointed out.
I did not point out any minor particulars, I listed the things that make
applying any concept of "associate arrays" acquired in any other
language to javascript's Objects a disappointing and unsuccessful
exercise.
But almost any language has such specific points:
http://en.wikipedia.org/ ...
Wikipedia again? Weren't they the ones that defined an associative array
as "a mapping from property names to values"? (That is actually a
description of nearly every object in any OO language).
And that doesn't mean that the principle of "associative
arrays" isn't the same across those languages.
State a definition of "associative array" that includes the things that
are associative arrays and precludes the things that are not and, if it
is successful/acceptable, we can see if the javascript Object qualifies
or not.
If declaration, assignment, key/value, representation,
syntactical appearance, look-up methodology and general
working of such variables all correspond to the
computer-scientific idea of "associative arrays", then I
would vote to name them as such in javascript too.
So would I, but javascript Objects don't so it is better to tell it like
it is.

Javascript objects are not a safe storage medium for arbitrary key/value
pairs and should not be treated as if they are. If such an object is
wanted it should be (and certainly can be) implemented with javascript.

Richard.
Aug 19 '06 #14

P: n/a
Richard Cornford wrote:
Javascript objects are not a safe storage medium for arbitrary
key/value pairs and should not be treated as if they are.
That's a bit of an exaggeration, isn't it?

Using an Object() to store key/value pairs is just fine as long as you don't
extend the Object prototype, don't expect keys back in any certain order,
etc.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 19 '06 #15

P: n/a
Matt Kruse wrote:
Richard Cornford wrote:
>Javascript objects are not a safe storage medium for
arbitrary key/value pairs and should not be treated
as if they are.

That's a bit of an exaggeration, isn't it?
No, it is a statement of fact.
Using an Object() to store key/value pairs is just fine
as long as you don't extend the Object prototype, don't
expect keys back in any certain order, etc.
The 'etc' includes; don't expect to be able to safely store and retrieve
values using _arbitrary_ property names.

Richard.
Aug 19 '06 #16

P: n/a
"Richard Cornford" <Ri*****@litotes.demon.co.ukwrites:
Matt Kruse wrote:
>Using an Object() to store key/value pairs is just fine
as long as you don't extend the Object prototype,
(and nobody else extends Object.prototype either)
>don't expect keys back in any certain order, etc.
The 'etc' includes; don't expect to be able to safely store and retrieve
values using _arbitrary_ property names.
The problem isn't storing a property and retrieving it again, which
works for all property names, it's recognizing what has been stored
without knowing the property names already.

Correct ECMAScript implementations gives you a "hasOwnProperty" that
can distinguish properties set on the object from those inherited from
its prototypes (but you would obviously have to call it indirectly,
like "Object.prototype.hasOwnProperty.call(myObject , propName)" as
it too could have been overridden on myObject).

That is the kind of loops you have to jump through to be able to
ignore inherited properties.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 20 '06 #17

P: n/a
Lasse Reichstein Nielsen wrote:
"Richard Cornford" <Ri*****@litotes.demon.co.ukwrites:
>Matt Kruse wrote:
>>Using an Object() to store key/value pairs is just fine
as long as you don't extend the Object prototype,

(and nobody else extends Object.prototype either)
>>don't expect keys back in any certain order, etc.
>The 'etc' includes; don't expect to be able to safely store
and retrieve values using _arbitrary_ property names.

The problem isn't storing a property and retrieving it again,
which works for all property names, it's recognizing what has
been stored without knowing the property names already.

The inability to safely use arbitrary keys as property names may not be
the problem but it certainly is a problem. Consider the following in a
JavaScript(tm) implementation:-

<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var o = {};

document.write(o.hasOwnProperty('_parent__')+'<br> <br>');
// writes - false - in JavaScript(tm)

document.write(o.__parent__+'<br><br>');
// writes - [object Window] - in JavaScript(tm)

o._parent__ = 'test 1'

document.write(o.hasOwnProperty('_parent__')+'<br> <br>');
// writes - true - in JavaScript(tm)

document.write(o.__parent__+'<br><br>');
// writes - [object Window] - in JavaScript(tm)

delete o.__parent__;

document.write(o.__parent__+'<br><br>');
// writes - [object Window] - in JavaScript(tm)

document.write(o.hasOwnProperty('_parent__')+'<br> <br>');
// writes - true - in JavaScript(tm)

document.write('----------------------'+'<br><br>');

o = {
'_parent__':'test 2'
};
document.write(o.hasOwnProperty('_parent__')+'<br> <br>');
// writes - true - in JavaScript(tm)

document.write(o.__parent__+'<br><br>');
// writes - [object Window] - in JavaScript(tm)

o._parent__ = 'test 3'

document.write(o.__parent__+'<br><br>');
// writes - [object Window] - in JavaScript(tm)

delete o.__parent__;

document.write(o.__parent__+'<br><br>');
// writes - [object Window] - in JavaScript(tm)

document.write(o.hasOwnProperty('_parent__'));
// writes - true - in JavaScript(tm)

</script>
</body>
</html>

- The extension(s) to the Object in JavaScript(tm) are legal, and the
extended properties are allowed to be - DontDelete - and - ReadOnly -
(even this strange form where assignment to the object moves the -
ReadOnly - value from the prototype to the object itself but makes the
new property of the object - DontDelete -).

So you cannot define, assign or retrieve values from Objects using
string keys safely unless you know enough about those string keys to be
pretty certain that they will never coincide with language extension
properties. That is; any keys used in this way must not be truly
arbitrary.

I think that the ability to use arbitrary keys is fairly fundamental to
what an "associative array" is, and so the javascript Object does not
qualify.
Correct ECMAScript implementations gives you a "hasOwnProperty"
that can distinguish properties set on the object from those
inherited from its prototypes (but you would obviously have to
call it indirectly, like
"Object.prototype.hasOwnProperty.call(myObject , propName)"
as it too could have been overridden on myObject).

That is the kind of loops you have to jump through to be able
to ignore inherited properties.
And in reality 90% of the time it is not an issue. For example, some of
the web service responses that the code I am working on at the moment
include sequences of name/value pairs. I have absolutely no qualms about
transferring those names to properties of javascript objects and the
values to their values, because those names are _required_ to satisfy a
format of uppercase alphabetical characters and (non-leading)
underscores only.

In other places values come in and I still want to use them as keys, but
not having certainty about what the character sequences represent I
store them in a (Java-style) 'HashTable' implementation.

It is knowing what the javascript object actually is that allows
informed decisions to be made about which hoops need to be jumped
through, and when.

Richard.
Aug 20 '06 #18

P: n/a
JRS: In article <ec*******************@news.demon.co.uk>, dated Sat, 19
Aug 2006 11:07:06 remote, seen in news:comp.lang.javascript, Richard
Cornford <Ri*****@litotes.demon.co.ukposted :
>
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.
ECMA there clearly implies that there is an order, by saying "next
property"; and it rather strongly suggests that the order does not
change if the Object is not changed.

Thus if an Object is enumerated twice without being changed in between,
the properties should be given in the same order; and in particular the
order is not randomly chosen during each enumeration. Which is only
reasonable.

Perhaps ECMA 4 will be more explicit - anyone here writing it?

--
© John Stockton, Surrey, UK. ??*@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.
In MS OE, choose Tools, Options, Send; select Plain Text for News and E-mail.
Don't quote more than is needed, and respond after each quoted part.
Aug 20 '06 #19

P: n/a
Hi,

Lasse Reichstein Nielsen wrote:
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.
C#'s Hashtables are also not sorted. If you do a "foreach" on a
Hashtable, it's impossible to predict in what order they will appear.

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Aug 20 '06 #20

P: n/a
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.javascript point of view very
questionable.

--
Bart

Aug 23 '06 #21

P: n/a
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.javascript 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 "associative 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

P: n/a
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.javascript 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 "associative 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.

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

P: n/a
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.javascript 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 "associative 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.
"Associative 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

P: n/a
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 "associative 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

P: n/a
"Matt Kruse" <ne********@mattkruse.comwrites:
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

P: n/a
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 misunderstanding 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 "associative 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

P: n/a
Arnaud Diederen aundro wrote:
"Matt Kruse" <ne********@mattkruse.comwrites:
>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.someProperty;

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

P: n/a
"Richard Cornford" <Ri*****@litotes.demon.co.ukwrites:
>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.prototype - 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.prototype.

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@ionicsoft.com
http://www.ionicsoft.com
Aug 23 '06 #29

P: n/a
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
misunderstanding 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.javascript 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

P: n/a
Richard Cornford wrote:
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 who is to make this definition? You? Because clearly the common
understanding used by Microsoft, Netscape, Sun, etc is different than yours.
And I would argue that their opinions carry more weight than yours, even if
you are technically more correct.

The difference is, you're looking to define something with absolute
certainty, whereas the term "associative array" is often casually used to
refer to "an object holding key/value pairs". Even if you disagree with the
common use of the term, you can't just choose to ignore it.
It is things like that that leave me having no regard for your
opinion. "Reserved word" has an absolutely precise meaning.
That's why I put it in quotes. Meaning, similar to but not identical to
Reserved Words. And I knew you would object.
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.
Maybe they are your pre-conceptions. Maybe most people looking for a simple
key/value pair construct and using the term "associative array" don't have
those pre-conceptions.
>Now, wouldn't that be more helpful?
In what sense?
Instead of just arguing over terminology and being anal retentive when you
_KNOW_ what the intent of the question is, try to provide a more helpful
answer instead.

We all know that you know the inner working of javascript better than most
people in the world, Richard. You can stop trying to prove that. You have
the opportunity to work long hours exclusively on javascript coding and
digging deep into the language. Most people will never have such an
opportunity. So instead of using your knowledge to belittle people and
constantly point out minor errors in terminology and language quirks, it
would be far more helpful to most if you could bridge the gap between a
typical person's understanding of javascript (given limited exposure to the
language, limited time to work on it, and often a very specific task to
complete) and a deeper more correct understanding and use of the language.

When you see someone ask "How can I implement an associative array in
javascript" you shouldn't think "what an idiot, there are no associative
arrays in javascript because that term implies X, Y, and Z, and there are
specific non-arbitrary keys that will cause problems!". Instead, think "what
he probably wants is a simple way to store key/value pairs. I'll explain how
to use a simple Object but also warn of some behaviors and quirks that might
confuse him if he happens to trip on them."

That would be more helpful. Just MO.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 23 '06 #31

P: n/a
Matt Kruse wrote:
Richard Cornford wrote:
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 who is to make this definition?
I am inviting Bart Van der Donck to attempt to write the definition. I
am doing so in order that he discovers for himself that any detention
that attempts to discriminate between things that are associative
arrays and things that are not is going to put the javascript object in
the _not_ associative array side.
You?
I have suggested a starting point, but inevitable it puts the
javascript object outside of the categorisation.
Because clearly the common
understanding used by Microsoft,
Microsoft? You are joking?
Netscape, Sun, etc is different than yours.
I have not seen any clear statement from any as to what an associative
array is.
And I would argue that their opinions carry more weight than
yours, even if you are technically more correct.
You probably would.
The difference is, you're looking to define something with absolute
certainty,
No, I am looking to demonstrate that any attempt to pin down what an
associative array is, in such a way as to exclude things that are not
associative arrays, will exclude the javascript object. The final
definition does not have to be complete, absolute or definitive. It is
the exercise of seeking it that will make my point for me.
whereas the term "associative array" is often casually used to
refer to "an object holding key/value pairs".
So that would be a definition that does not exclude the Java Vector
(which is an object that really should not be categorised as an
associative array). Do you see why I am doing this yet? You can have
your casual definition that may include javascript objects, but it will
be so loose as to be useless as things will be included that really
should not be called associative arrays.

The question that remains to be answered is whether there is a
discriminating definition of an associative array that excludes things
that should not be included like the Java Vector but can accommodate
the javascript object. I will not be you who will be proposing such a
discriminating definition.
Even if you disagree with the common use of the
term, you can't just choose to ignore it.
I can point out that it is so loose that it includes things that most
people would never accept as reasonably categorised "associative
arrays".
>It is things like that that leave me having no regard for your
opinion. "Reserved word" has an absolutely precise meaning.

That's why I put it in quotes. Meaning, similar to but not identical
to Reserved Words. And I knew you would object.
Your attribution of meaning to English is sometimes extremely odd.
>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.

Maybe they are your pre-conceptions.
What are my pre-conceptions?
Maybe most people looking for a simple key/value pair
construct and using the term "associative array" don't have
those pre-conceptions.
Maybe most don't (who could say), but the many who do are the ones
being harmed by the inappropriate use of the term in association with
javascript objects. It is, after all, the consequences of their
misconceptions that motivates people to post the questions to the group
that give the impression that "associative array" thinking is a problem
causer when applied to javascript objects.
>>Now, wouldn't that be more helpful?
>In what sense?

Instead of just arguing over terminology
So the incoherent sentence is not going to be clarified?
and being anal retentive when you _KNOW_ what the
intent of the question is, try to provide a more helpful
answer instead.
Why don't you? Except maybe given that previous proposed response, its
incoherent nature and your mercenary attitude towards English meaning,
you couldn't be much help in improving anyone's understanding anyway.

<snip>
When you see someone ask "How can I implement an associative
array in javascript" you shouldn't think "what an idiot, there are no
associative arrays in javascript because that term implies X, Y, and
Z, and there are specific non-arbitrary keys that will cause
problems!".
Is that what I would think? Surly if someone asks how to implement an
associative array in javascript the one assumption that can be made is
that they do not believe that Javascript already has associative
arrays, else the question would be redundant?
Instead, think "what he probably wants is a simple way to
store key/value pairs.
No. If someone asks how to implement an associative array in javascript
I am going to assume that they want to be able to store any value under
an arbitrary string key, retrieve any stored values using that key and
remove the key and its corresponding value form that storage. The
simplicity/complexity of the end result is a product of what it would
have to do, not be pre-supposed by the fact that the question was
asked.
I'll explain how to use a simple Object but also warn of some
behaviors and quirks that might confuse him if he happens to
trip on them."
Right, assume the questioner doesn't really want what they are asking
for and suggest something that will only 'mostly work'.
That would be more helpful. Just MO.
And if they really wanted an associative array, and the ability to use
arbitrary keys safely, you will have wasted your own time, their time,
and possible their development effort as they go off down a dead end
and then work their way back to where they started.

There a no blanket prescription for 'more helpful'. If a question is
asked in a way that informs the reader of the context in which it is
asked it is likely better answered than if not. As soon as we are in
the world of assumptions you cannot tell if a simple quick hack is will
be most appropriate, or a pending disaster.

Richard.

Aug 23 '06 #32

P: n/a
Richard Cornford wrote:
No, I am looking to demonstrate that any attempt to pin down what an
associative array is, in such a way as to exclude things that are not
associative arrays, will exclude the javascript object.
Wouldn't a definition of an associative array necessarily exclude everything
not in the definition? Isn't that the whole point of a definition?
So that would be a definition that does not exclude the Java Vector
(which is an object that really should not be categorised as an
associative array).
Try this:

"An associative array is a collection of unordered values/objects which
allows for the storage and retrieval of a value/object [Value] using a
user-defined value/object [Key] as the only storage/retrieval criteria, such
that retrieving a Value stored for a given Key will return the Value
previously stored for the given Key."

That would include the javascript Object, exclude js Array, and exclude
Vector (since both are ordered). It doesn't say the object cannot have
additional properties of its own, or that retrieving keys which were not
stored would be required to return nothing, or that the user-defined keys
may be completely arbitrary. If you expect those to be part of a definition,
maybe you have too many pre-conceptions about associative arrays.
So the incoherent sentence is not going to be clarified?
Extremely maybe.
Why don't you? Except maybe given that previous proposed response, its
incoherent nature and your mercenary attitude towards English meaning,
you couldn't be much help in improving anyone's understanding anyway.
Do you completely lack a personality, or does it simply not come through in
text?
Surly if someone asks how to implement an
associative array in javascript the one assumption that can be made is
that they do not believe that Javascript already has associative
arrays, else the question would be redundant?
No, they are probably just seeking the language-specific implementation of
the concept. Much like someone new to VB may not find the Dictionary object
but they do know what they want.
No. If someone asks how to implement an associative array in
javascript I am going to assume that they want to be able to store
any value under an arbitrary string key, retrieve any stored values
using that key and remove the key and its corresponding value form
that storage.
Why do you assume a string key? Why don't you assume they want to key based
on any arbitrary Object like in Java? Your assumptions seem to be just those
required to arrive at your conclusion.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 23 '06 #33

P: n/a
Matt Kruse wrote:
Richard Cornford wrote:
>No, I am looking to demonstrate that any attempt to pin down what
an associative array is, in such a way as to exclude things that are
not associative arrays, will exclude the javascript object.

Wouldn't a definition of an associative array necessarily exclude
everything not in the definition? Isn't that the whole point of a definition?
Yes, but would any given definition exclude all of those things that
are evidently not associative arrays and include all those things that
are?
>So that would be a definition that does not exclude the Java Vector
(which is an object that really should not be categorised as an
associative array).

Try this:

"An associative array is a collection of unordered values/objects which
allows for the storage and retrieval of a value/object [Value] using a
user-defined value/object [Key] as the only storage/retrieval criteria, such
that retrieving a Value stored for a given Key will return the Value
previously stored for the given Key."
You have left "user-defined value/object [key] so open that it is not
possible to eliminate many objects. If "user-defined" is allowed to
include, say, a limited set of non-arbitrary strings then many hundreds
of objects could start to qualify. Suppose a 'user' (read programmer)
defines a Java class has two named public instance members of Object
type, then you can regard the names of those members as keys with witch
you can store values in the object, and retrieve them from it. The
result is unordered, can have values stored/ retrieved using those keys
as the only criteria and the given key will return the value previously
sorted with that key.
That would include the javascript Object,
That would depend on what you mean by "user-defined value/object
[key]". If "user-defined" is intended to indicate that the user may
define anything (or anything reasonable in the context (so any string
key in the case of javascript objects)) then the fact that you cannot
reliably store values in objects using any key, or subsequently
retrieve those values form objects using the same key, then javascript
objects do not qualify.
exclude js Array,
As JS Arrays are JS Objects, how does it manage that?
and exclude
Vector (since both are ordered).
Ah, you have explicitly put "a collection of unordered values/objects"
in your definition so that you can exclude Vectors. But for that to
work you have to exclude any associative arrays that are ordered in any
way, and this very thread demonstrates that consistent ordering in
enumeration is not only something that is expected of associative
arrays but also a feature of javascript object implementations. That
is, javascript object properties have been demonstrated to be available
in the order in which they were added to the object, and the OP reports
an associative arrays that orders its keys alphabetically.
It doesn't say the object cannot have additional properties
of its own, or that retrieving keys which were not
stored would be required to return nothing,
Which is a considerable compromise.
or that the user-defined keys may be completely arbitrary.
If you are not allowed all permutations of possible keys then only
being allowed as few as two string keys qualifies, and thousands of
objects suddenly become associative arrays. You have really just fudged
the question of the keys.
If you expect those to be part of a definition,
maybe you have too many pre-conceptions about
associative arrays.
I suspect that if you asked most of the people who use associative
arrays they would find the idea of being able to use some keys of one
type, and not others of the same type, completely alien.
>So the incoherent sentence is not going to be clarified?

Extremely maybe.
Why don't you? Except maybe given that previous proposed response, its
incoherent nature and your mercenary attitude towards English meaning,
you couldn't be much help in improving anyone's understanding anyway.

Do you completely lack a personality, ...
Ahh, personal abuse.
>Surly if someone asks how to implement an associative
array in javascript the one assumption that can be made is
that they do not believe that Javascript already has associative
arrays, else the question would be redundant?

No, they are probably just ... .
Be cautions of accusing others of making assumptions when you are so
happy to do so yourself.
>No. If someone asks how to implement an associative array in
javascript I am going to assume that they want to be able to store
any value under an arbitrary string key, retrieve any stored values
using that key and remove the key and its corresponding value form
that storage.

Why do you assume a string key?
If anything is stored as a property of an object in javascript it is a
string that is used as the key.
Why don't you assume they want to key based
on any arbitrary Object like in Java?
That would be more of a HashTable than an associative array. When the
question of implementing HashTable in javascript has arisen I have
explained how to key them with objects. To date nobody has expressed an
interest in implementing an associative array as such.
Your assumptions seem to be just those
required to arrive at your conclusion.
At least the end result would be consistent rather than just "mostly
works".

Richard.

Aug 23 '06 #34

P: n/a
"Richard Cornford" <Ri*****@litotes.demon.co.ukwrites:
Property names are only strings in the sense of being sequences of zero
or more characters.
The actual property names of objects can be any value (in ECMAScript
3ed), but the language itself only gives access to operations that
use string values as property names. These are string in the sense
of being values of the String type (typically results of the ToString
function).
If a property of an object is accessed as:-

var val = obj.someProperty;

- the - someProperty - is not a string (in the sense of being a
javascript string primitive or String Object), it is an Identifier.
True, but the identifier is not the property name being used to
access the objects property. A string value containing the same
characters is.
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.
True. The [[Get]] and [[Put]] functions doesn't make any restrictions
on what can be a "property name". It's not possible with pure ECMAScript
to have those methods called with anything but a string, though.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Aug 23 '06 #35

P: n/a
Richard Cornford wrote:
I am inviting Bart Van der Donck to attempt to write the definition. I
am doing so in order that he discovers for himself that any detention
that attempts to discriminate between things that are associative
arrays and things that are not is going to put the javascript object in
the _not_ associative array side.
[...]
Can find myself in 2 'official' definitions from the N.I.S.T.:

"A collection of items that are randomly accessible by a key, often a
string."
(http://www.nist.gov/dads/HTML/assocarray.html)

"An abstract data type storing items, or values. A value is accessed by
an associated key. Basic operations are new, insert, find and delete."
(http://www.nist.gov/dads/HTML/dictionary.html)

Surprisingly broad, isn't it ? But I think this should be about as far
as you can go; further specifications quickly lead to language-specific
implementations.

--
Bart

Aug 23 '06 #36

P: n/a
Bart Van der Donck wrote:
Richard Cornford wrote:
>I am inviting Bart Van der Donck to attempt to write the
definition. I am doing so in order that he discovers for
himself that any detention that attempts to discriminate
between things that are associative arrays and things that
are not is going to put the javascript object in the _not_
associative array side.
[...]

Can find myself in 2 'official' definitions from the N.I.S.T.:

"A collection of items that are randomly accessible by a key,
often a string."
(http://www.nist.gov/dads/HTML/assocarray.html)

"An abstract data type storing items, or values. A value is
accessed by an associated key. Basic operations are new,
insert, find and delete."
(http://www.nist.gov/dads/HTML/dictionary.html)

Surprisingly broad, isn't it ?
That doesn't matter. The question is still just whether these
definitions include things that should not be regarded as associative
arrays, such as the Java Vector, or exclude the javascript object.
Neither excludes the Java Vector, so are not really that discriminating.
Being able to label something that is conceptually an array as an
"associative array" is quite a price to pay in order to label something
that should not be thought of as one an associative array.

Where the second says "an associated key" it ether means 'any associated
key' and so excludes the javascript object, as it cannot store and
access values (or items) by any associated key, or delete them (That is,
some key will not store, cannot retrieve stored values (as they were
never stored) and cannot be deleted), or "an associated key" means 'a
specific associated key', and any Java class that has a public member is
included.

So either an associative array is so broad a concept that the label
could be applied to all sorts of things (so probably better not used at
all), or it does not apply to javascript objects.
But I think this should be about as far as you can
go; further specifications quickly lead to
language-specific implementations.
I don't think that is true. A much more specific definition could be
written. I still think the answer lies in the nature of the keys; that
if of a type then all values of that type, and if of many types all
values of all allowed types (i.e. if a string then any arbitrary
character sequence as a string). The key is itself an aspect of the
data, and so cannot be more restricted than the data. It is a
significant aspect of this type of storage that you don't need to know
the actual value of the key when you use it (even if you may need to
know its type, or that it is of the right type(s)). It is that aspect of
the issue that excludes the javascript object, and making the definition
of a key so vague as to avoid making it obvious that the javascript
object is excluded just makes the concept so loose as to allow all sorts
of things to be included.

Another approach to a reasonable definition of an associative array may
be to look that those objects in languages that can be agreed to have
them and see what is common among them.

Richard.
Aug 23 '06 #37

P: n/a
Richard Cornford said the following on 8/23/2006 6:49 AM:
Bart Van der Donck wrote:
<snip>
>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.
And, how many associative array implementations don't increase the
..length property of the array when you add an element?

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Aug 23 '06 #38

P: n/a
Randy Webb wrote:
And, how many associative array implementations don't increase the
.length property of the array when you add an element?
I would put that into the "doesn't matter" category, as I don't think it
should be a requirement of an associative array to have a size or length
property/accessor.

Perhaps what should be added to my proposed definition is that any
associative array should have a way to retrieve a list of all keys. Which,
of course, you can do with a javascript Object.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 23 '06 #39

P: n/a
Matt Kruse wrote:
Randy Webb wrote:
>And, how many associative array implementations don't increase
the .length property of the array when you add an element?

I would put that into the "doesn't matter" category, as I don't
think it should be a requirement of an associative array to
have a size or length property/accessor.

Perhaps what should be added to my proposed definition is that
any associative array should have a way to retrieve a list of
all keys. Which, of course, you can do with a javascript Object.
Not if a key is defined as something that can be used to reference an
associated value held by the object, as only enumerable properties would
be listed and the names of the non-enumerable properties would still
qualify as keys. (That is, if you want to allow pre-defined/pre-existing
key/value pairs, as you must if the javascript object is to be included
in the category, the keys for those properties should be included in a
list of "all keys" or it is not a list of all of the keys.)

Richard.
Aug 23 '06 #40

P: n/a
Richard Cornford wrote:
(That is, if you want to allow
pre-defined/pre-existing key/value pairs, as you must if the
javascript object is to be included in the category,
You needn't allow nor disallow pre-existing key/value pairs.
the keys for
those properties should be included in a list of "all keys" or it is
not a list of all of the keys.)
Replace "all keys" with "all user-defined keys" then, if you want to be
argumentative.

That leaves my definition from the earlier post (which you did not respond
to) as:

"An associative array is an unordered collection of values/objects which
allows for the storage and retrieval of a value/object [Value] using a
user-defined value/object [Key] as the only storage/retrieval criteria such
that retrieving a Value stored for a given Key will return the Value
previously stored for the given Key, and also supplying a method to retrieve
an unordered collection of all user-defined Keys."

Objections?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 24 '06 #41

P: n/a
Matt Kruse wrote:
Richard Cornford wrote:
>(That is, if you want to allow
pre-defined/pre-existing key/value pairs, as you must if the
javascript object is to be included in the category,

You needn't allow nor disallow pre-existing key/value pairs.
You need to either not disallow them or to exclude the javascript
object from being an associative array. Not disallowing is allowing.
>the keys for
those properties should be included in a list of "all keys" or it is
not a list of all of the keys.)

Replace "all keys" with "all user-defined keys" then, if you want to
be argumentative.
And in making the terms less precise you risk reducing the definition
to a point where it is so generally applicable as to be saying nothing
useful.
That leaves my definition from the earlier post (which you did not
respond to) as:
Your news server sounds like it has some catching up to do.
"An associative array is an unordered collection of values/objects
which allows for the storage and retrieval of a value/object [Value]
using a user-defined value/object [Key] as the only storage/retrieval
criteria such that retrieving a Value stored for a given Key will return
the Value previously stored for the given Key, and also supplying a
method to retrieve an unordered collection of all user-defined Keys."

Objections?
Personally I would not consider the ability to list all the keys as
fundamental to the concept of an associative array and so would not
like to see it in any definition. I also would not be too concerned to
require the object to know how many keys are in use (no matter how
common that may be in actual associative arrays). These are getting
towards the language specific aspects of the question that were warned
about yesterday.

However, it is not a question of objecting to any given definition
-presented as such, but instead seeing how well it discriminates
objects that objectively are associative arrays from those that are
not, and whether it puts the javascript object on the associative array
side of that demarcation.

Again the vagary in "user-defined value/object [Key]" leaves the actual
nature of the keys completely open, and so includes many objects that
are not associative arrays. However, as the object that is to be
considered an associative array by this definition must provide a
method to "retrieve an unordered collection of all user-defined Keys"
the keys that could be returned from such a method act to define what
is a "user-defined" key.

The javascript object only provides one method that could be this
method to "retrieve an unordered collection of all user-defined Keys",
and that is the - for-in - loop. Thus a "user-defined" key becomes any
property name that once added to the object is then enumerated by a
for-in loop (how well that for-in satisfies your demand that it be
unordered is not important here). Thus the javascript object is
categorised as not being an associative array by your definition as
there are keys that will be enumerated following an attempt to use them
for assignment of a value to a new property of the object that cannot
be used to retrieve the value assigned during that assignment ("such
that retrieving a Value stored for a given Key will return the Value
previously stored for the given Key" is false for keys that will be
enumerated by for-in and so need to qualify as "user-defined" in order
to satisfy "also supplying a method to retrieve an unordered collection
of all user-defined Keys").

(We also get to quibble again about how ordered/unordered examples of
actual associative arrays may be, and how ordered/unordered the
javascript object actually is, but that is not important here as the
javascript object is already excluded by this definition).

Richard.

Aug 24 '06 #42

This discussion thread is closed

Replies have been disabled for this discussion.