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

Object as key for associative array

P: n/a
Is it possible to have an Object as the key for an Associative array
like in the following example....
function Obj(var1, var2)
{
this.var1 = var1;
this.var1 = var1;
}
function test() {
var sectionArray = new Array();
var obj = new Obj("c","k");
var obj2 = new Obj("3","n");
var obj3 = new Obj("v","qk");

sectionArray[obj] = "king";
sectionArray[obj2] = "queen";
sectionArray[obj3] = "joker";
alert(sectionArray[obj]);
}

This does not give any error but the alert says "joker" instead of
"king". Is there anything wrong with my code or is an Object something
that just can not be used as a key.

If it is the latter can someone please suggest another way for me to do
it? Can I use a concatenated String instead of an object? My only
problem then is how would I extract the values from the String, does
JavaScript have a tokenizer method like Java?

Thanks for any help.

Jul 23 '05 #1
Share this Question
Share on Google+
11 Replies


P: n/a
Lee
Je*******@aol.com said:

Is it possible to have an Object as the key for an Associative array
like in the following example....
function Obj(var1, var2)
{
this.var1 = var1;
this.var1 = var1;
}
function test() {
var sectionArray = new Array();
var obj = new Obj("c","k");
var obj2 = new Obj("3","n");
var obj3 = new Obj("v","qk");

sectionArray[obj] = "king";
sectionArray[obj2] = "queen";
sectionArray[obj3] = "joker";
alert(sectionArray[obj]);
}

This does not give any error but the alert says "joker" instead of
"king". Is there anything wrong with my code or is an Object something
that just can not be used as a key.

If it is the latter can someone please suggest another way for me to do
it? Can I use a concatenated String instead of an object? My only
problem then is how would I extract the values from the String, does
JavaScript have a tokenizer method like Java?


The index has to be a string, so Javascript converts your Object to a string
using the default toString() method, which returns "[Object]" (or something like
that). Define your own toString() method that returns a unique value.

And be aware that Javascript doesn't have true associative arrays. The
attribute names of any Object can be used as if they were indices to return
their values.

Jul 23 '05 #2

P: n/a
If you're trying to put objects into an associative array without a
unique key, then there is probably something wrong with your concept of
the data structure. Maybe try something like this, which is an
associative hash of objects, keyed by a string. (Note that JS1.2
object literal/initializer syntax allows you to specify both the
properties and values in-line. Also, note two ways to reference the
object.)

var cards = {
"king": { num:13, let:"k" },
"queen": { num:12, let:"q" },
"jack": { num:11, let:"j" }
};

alert('queen is: '+cards["queen"].num+' '+cards.queen.let);

Jul 23 '05 #3

P: n/a
Can you show me how to define the toString () method ?

Jul 23 '05 #4

P: n/a
function Obj(var1, var2) {
this.var1 = var1;
this.var2 = var2;
}

var obj = new Obj("c","k");
var obj2 = new Obj("3","n");

Obj.prototype.toString = function() {
return this.var1+' '+this.var2;
}

alert(obj.toString());
alert(obj2.toString());

(Tested)

BTW, a great reference for Javascript can be found in an unlikely
place, the Windows Scripting Reference .chm help file. The index is
very handy.

http://tinyurl.com/7rk6 - Download Windows Scripting Reference

Jul 23 '05 #5

P: n/a
humbads wrote:
function Obj(var1, var2) {
this.var1 = var1;
this.var2 = var2;
}

var obj = new Obj("c","k");
var obj2 = new Obj("3","n");

Obj.prototype.toString = function() {
return this.var1+' '+this.var2;
}

alert(obj.toString());
alert(obj2.toString());

(Tested)


The most interesting thing about the alert() method is that it automatically
converts the argument to string *for display* [in all UAs that implement
DOM Level 0 which actually defines alert()], using its toString() method if
such is defined. So the special call of toString() here is unnecessary and
thus reduces performance.
PointedEars
--
Faulheit und Feigheit sind die beiden Ursachen, warum ein Teil der Menschen
[...] gerne zeitlebens unmündig bleibt, und warum es anderen so leicht wird,
sich zu deren Vormündern aufzuwerfen. Es ist so bequem, unmündig zu sein.
-- Immanuel Kant
Jul 23 '05 #6

P: n/a
Thomas 'PointedEars' Lahn <Po*********@web.de> writes:
alert(obj.toString());
.... The most interesting thing about the alert() method is that it automatically
converts the argument to string *for display* [in all UAs that implement
DOM Level 0 which actually defines alert()],
(if "DOM Level 0" was itself defined in any way sufficient to give it
a name ... i.e., alert is an entirely de-facto standard with no common,
official definition)
using its toString() method if such is defined.
Probably uses internal conversion, equivalent to doing:
String(object)
rather than:
object.toString()
which also allows for "null" and "undefined" values. That will, in turn,
call toString *if* the argument is an object.

But that's just pedantism, for the actual arguments of this example,
the statement is correct.
So the special call of toString() here is unnecessary and thus
reduces performance.


Unnecessary, yes. Reduces performance ... no. It's hard to reduce the
performance of something that blocks for user input :)

/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.'
Jul 23 '05 #7

P: n/a
Lasse Reichstein Nielsen wrote:
Thomas 'PointedEars' Lahn <Po*********@web.de> writes:
alert(obj.toString());
[...] The most interesting thing about the alert() method is that it
automatically converts the argument to string *for display* [in
all UAs that implement DOM Level 0 which actually defines alert()],


(if "DOM Level 0" was itself defined in any way sufficient to give it
a name ... i.e., alert is an entirely de-facto standard with no common,
official definition)


,-<http://www.w3.org/TR/DOM-Level-2-HTML/glossary.html>
|
| [...]
| DOM Level 0
| The term "DOM Level 0" refers to a mix (not formally specified) of
| HTML document functionalities offered by Netscape Navigator version
| 3.0 and Microsoft Internet Explorer version 3.0. In some cases,
| attributes or methods have been included for reasons of backward
| compatibility with "DOM Level 0".

DOM Level 0, components of it defined in the Netscape JavaScript 1.3
Reference, has been widely implemented in J(ava)Script-capable UAs
since IE3/NN3:

<http://web.archive.org/web/20040202050531/devedge.netscape.com/library/manuals/2000/javascript/1.3/reference/>
<http://web.archive.org/web/200402141...w.html#1201497
[...]
So the special call of toString() here is unnecessary and thus
reduces performance.


Unnecessary, yes. Reduces performance ... no. It's hard to reduce the
performance of something that blocks for user input :)


Well, the alert() window will disappear a little time later than without it.
This *is* a degradation of performance, yet not a significant one for *one*
call. Furthermore, do you know a reference that states alert() windows
should not be displayed asynchronically?
PointedEars
Jul 23 '05 #8

P: n/a
Thomas 'PointedEars' Lahn wrote:
Well, the alert() window will disappear a little time later than without
it. [...]


Err, s/dis//
PointedEars
Jul 23 '05 #9

P: n/a
Thomas 'PointedEars' Lahn <Po*********@web.de> writes:
Lasse Reichstein Nielsen wrote:
(if "DOM Level 0" was itself defined in any way sufficient to give it
a name ... i.e., alert is an entirely de-facto standard with no common,
official definition)


,-<http://www.w3.org/TR/DOM-Level-2-HTML/glossary.html>
|
| [...]
| DOM Level 0


Ok, I'll have to admit that "DOM Level 0" is a name that *is* being
used by even the W3C, albeit to refer to a non-defined subset of
(non-standardized) functionality of earlier browsers.

The name is misleading, because it suggests that there is a definition
(as for DOM levels 1 and 2) and that it has something to do with
documents (the D in DOM).
DOM Level 0, components of it defined in the Netscape JavaScript 1.3
Reference, has been widely implemented in J(ava)Script-capable UAs
since IE3/NN3:
There are lots of features defined in these documents. Some are in the
set commonly considered DOM Level 0, others aren't (e.g., the java*
objects, layers, watch/unwatch methods on objects, etc.). If there
is a consensus about what DOM Level 0 contains at all, that is.
Unnecessary, yes. Reduces performance ... no. It's hard to reduce the
performance of something that blocks for user input :)


Well, the alert() window will disappear a little time later than without it.
This *is* a degradation of performance, yet not a significant one for *one*
call.

[correcte to "appear a little time later" in other post]

Not for any amount of calls. The millisecond extra time is dwarfed by
the time it takes for user interaction. More time is wasted if the
user blinks while reading the message.
Furthermore, do you know a reference that states alert() windows
should not be displayed asynchronically?


That would bring me back to the "no common official definition" :)

DOM Level 0, as the term is used by the W3C, refers to Netscape
Navigator 3 (JavaScript v1.1) and IE 3 (JScript v2).

You pointed out the definition of alert() in JavaScript v1.1, which
doesn't say anything about being synchroneous or asynchroneous. It
might be implicit in calling it a "dialog window".

The JScript definition is:
URL:http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/alert.asp>
It says even less (but does say: "There is no public standard that applies to this method.")
The most current definition would be the Gecko DOM reference, which is
also the only one to classify methods as "DOM Level 0. Not part of
specification". It says less than the JavaScript 1.1 reference.
<URL:http://www.mozilla.org/docs/dom/domref/dom_window_ref2.html#1016766>

So, no, alert() could be asynchroneous without braking anything but
tradition. But I guess that's what DOM Level 0 is: A name for "how
it traditionally is".

/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.'
Jul 23 '05 #10

P: n/a
> But I guess that's what DOM Level 0 is: A name for "how
it traditionally is".

My Oreilly Javascript book (4th edition) says, "... the Document
objects that have become de facto standards ... are known as the Level
0 DOM, because they form a base level of document functionality that
Javascript programmers can rely on in all browsers."

Therefore, no standards setting organization (SSO) has defined Level 0
DOM, but since you can expect those objects in all browsers, it is a de
facto standard. I think that a de facto standard is just as
well-defined as an SSO-ratified standard, for all practical purposes.
And I think the name is appropriate too, even if slightly misleading.

Just my two cents.

Jul 23 '05 #11

P: n/a
humbads wrote:
But I guess that's what DOM Level 0 is: A name for "how
it traditionally is".


My Oreilly Javascript book (4th edition) says, "... the
Document objects that have become de facto standards ...
are known as the Level 0 DOM, because they form a base
level of document functionality that Javascript programmers
can rely on in all browsers."

Therefore, no standards setting organization (SSO) has
defined Level 0 DOM, but since you can expect those
objects in all browsers, it is a de facto standard.
I think that a de facto standard is just aswell-defined
as an SSO-ratified standard, for all practical purposes.
And I think the name is appropriate too, even if slightly
misleading.

<snip>

The problem with asserting that an unwritten DOM level 0 is a de facto
standard is that you don't know what exactly it is that is in that
standard. If you define it as 'the features you can expect to find in
all browsers, and are not explicitly defined an any real standards',
then you can 'rely on those features in all browsers'. But you then need
to be familiar with the DOMs of *all* browsers in order to know what is
in that 'level 0 standard' and what is not (Which is not a realistic
requirement).

Take the global - Option - constructor, for example. Many would
categorise it as DOM level zero but you will not find it on NetFront 4.

Richard.
Jul 23 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.