473,396 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Object as key for associative array

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
11 13970
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
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
Can you show me how to define the toString () method ?

Jul 23 '05 #4
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
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
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
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
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
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
> 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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference...
5
by: mark4asp | last post by:
Suppose I wanted to create an array that was associative in 2 dimensions. The rows are associated with numbers. The columns with words. For instance for 3 columns. This array will have 20 rows...
26
by: JGH | last post by:
How can I check if a key is defined in an associative array? var users = new array(); users = "Joe Blow"; users = "John Doe"; users = "Jane Doe"; function isUser (userID) { if (?????)
4
by: Robert | last post by:
I am curious why some people feel that Javascript doesn't have associative arrays. I got these definitions of associative arrays via goggle: Arrays in which the indices may be numbers or...
14
by: Yereth Jansen | last post by:
Hi all, I encountered a problem with looping through an associative array. All worked perfectly with the following code: for (var menuItem in this.menuItems) { doSomething(); } where...
47
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they...
21
by: scandal | last post by:
I am a javascript newbie working on a script that checks whether a "path" from one element in an array to another is "blocked." Currently, the script pushes an already processed cell index (hence...
35
by: VK | last post by:
Whatever you wanted to know about it but always were affraid to ask. <http://www.geocities.com/schools_ring/ArrayAndHash.html>
7
by: Robert Mark Bram | last post by:
Hi All! How do you get the length of an associative array? var my_cars= new Array() my_cars="Mustang"; my_cars="Station Wagon"; my_cars="SUV"; alert(my_cars.length);
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.