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

How to assign variable value as the object property name?

P: n/a
How is it possible to take the value of a variable (in this case,
MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name?

In the following example I want 'oIcon' object to have the properties:
mode1, mode2, and mode3.

This seems simple but I can't quite figure it out...

Any ideas anyone?
var MODE_CREATE = "mode1";
var MODE_UPDATE = "mode2";
var MODE_DELETE = "mode3";

var oIcon = {
MODE_CREATE: "create.gif"
, MODE_UPDATE: "update.gif"
, MODE_DELETE: "delete.gif"
};

var oTitle = {
MODE_CREATE: "Create a new item..."
, MODE_UPDATE: "Update this item..."
, MODE_DELETE: "Delete this item..."
};

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


P: n/a
sn****@mxlogic.com wrote:
How is it possible to take the value of a variable (in this case,
MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name?

In the following example I want 'oIcon' object to have the properties:
mode1, mode2, and mode3.

This seems simple but I can't quite figure it out...

Any ideas anyone?
var MODE_CREATE = "mode1";
var MODE_UPDATE = "mode2";
var MODE_DELETE = "mode3";

var oIcon = {
MODE_CREATE: "create.gif"
, MODE_UPDATE: "update.gif"
, MODE_DELETE: "delete.gif"
};

var oTitle = {
MODE_CREATE: "Create a new item..."
, MODE_UPDATE: "Update this item..."
, MODE_DELETE: "Delete this item..."
};


Probably don't want to use an object *literal* for that purpose:
identifiers become property names without being evaluated. Try this:

<html>
<head>
<title>untitled</title>
</head>
<body>
<pre>
<script type="text/javascript">

var MODE_CREATE = "mode1";
var MODE_UPDATE = "mode2";
var MODE_DELETE = "mode3";

var oIcon = Object();
oIcon[MODE_CREATE] = "create.gif";
oIcon[MODE_UPDATE] = "update.gif";
oIcon[MODE_DELETE] = "delete.gif";

var oTitle = Object();
oTitle[MODE_CREATE] = "Create a new item...";
oTitle[MODE_UPDATE] = "Update this item...";
oTitle[MODE_DELETE] = "Delete this item...";

var a = [];
a.push('-oIcon-\n');
for (prop in oIcon)
a.push(prop + ': ' + oIcon[prop]);
a.push('\n-oTitle-\n');
for (prop in oIcon)
a.push(prop + ': ' + oTitle[prop]);
document.writeln(a.join('\n'));

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

Probably a more systematic way of doing this and avoiding repetition...

Jul 23 '05 #2

P: n/a


Well:

{eval(MODE_CREATE+': "create.gif"'),...}

yes, I do know, is not so preferred, but can't say I've checked other or
can see other ways offhand.

Danny

On Wed, 29 Jun 2005 11:33:43 -0700, <sn****@mxlogic.com> wrote:
How is it possible to take the value of a variable (in this case,
MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name?

In the following example I want 'oIcon' object to have the properties:
mode1, mode2, and mode3.

This seems simple but I can't quite figure it out...

Any ideas anyone?
var MODE_CREATE = "mode1";
var MODE_UPDATE = "mode2";
var MODE_DELETE = "mode3";

var oIcon = {
MODE_CREATE: "create.gif"
, MODE_UPDATE: "update.gif"
, MODE_DELETE: "delete.gif"
};

var oTitle = {
MODE_CREATE: "Create a new item..."
, MODE_UPDATE: "Update this item..."
, MODE_DELETE: "Delete this item..."
};


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Jul 23 '05 #3

P: n/a
Danny wrote:
Well:

{eval(MODE_CREATE+': "create.gif"'),...}

yes, I do know, is not so preferred, but can't say I've
checked other or can see other ways offhand.


It is often said, and more often true, that if you are considering using
the - eval - function in javascript you are missing something simpler,
faster, more direct and so objectively better.

Perhaps it might be an idea to find some time to learn javascript:-

<URL: http://www.jibbering.com/faq/ >

Richard.
Jul 23 '05 #4

P: n/a
VK
Yoop... It looks like {...} doesn't evaluate hash elements at the
creation time. I guess ECMA has a perfect (but useless for you)
explanation of this with a lot of numbers and cross-references.

You have to use then the RobB code.

Jul 23 '05 #5

P: n/a
Lee
VK said:

Yoop... It looks like {...} doesn't evaluate hash elements at the
creation time. I guess ECMA has a perfect (but useless for you)
explanation of this with a lot of numbers and cross-references.


Have you never used any programming language before (obviously,
you don't have much experience with newsreaders)?
You can't simply substitute variables where the syntax of the
language requires a literal.

Jul 23 '05 #6

P: n/a
VK
> Have you never used any programming language before

I used quite a lot of them for money.
No, I never received CS degree in a university (only MD in
linguistics). So if you want to consider me as an amateur, you have
your rights to do so.
You can't simply substitute variables where the syntax of the
language requires a literal. From my amateur look if I do: hashObject = {VAR_NAME1 : "foo", VAR_NAME2 : "bar"};
the interpreter should understand that non-quoted char combinations
(VAR_NAME1, VAR_NAME2) are names of variables. And it should substutute
it with the variable values instead.
It *shouldn't* think for me that I just have forgotten to put quotes
around (this is what it does right now). At least the interpreter
doesn't try to act out when I apply hashObject[VAR_NAME] = "foo"; I
would prefer to see it not trying to be overly smart in the first case
neither.

obviously, you don't have much experience with newsreaders


Actually I do. What exactly dusturbs you? That I didn't include OP's
testcase in my reply? Have you ever try to read >'ed / >>'ed code?
There is such great thing as *news thread* and usually you should read
it through to get the right picture, starting, of course, with OP
itself.
(Unless you think that in the very far future all this thread will be
removed as useless and only my ingenius reply will remain forever in
some galactical hall of fame... or a hall of shame :)

Jul 23 '05 #7

P: n/a
VK wrote:
From my amateur look if I do:
hashObject = {VAR_NAME1 : "foo", VAR_NAME2 : "bar"};
First of all, `hashObject' is gibberish. All JS objects could be
considered hashes, whether defined using an object literal or not.
the interpreter should understand that non-quoted char combinations
(VAR_NAME1, VAR_NAME2) are names of variables. And it should substutute
it with the variable values instead.


No, it should not, because that is a property name definition. Using the
value of the variable with that identifier would cause side effects if
one wants to declare a property with the same identifier. However, the
language fortunately does not require identifiers to be unique throughout
the entire program; it only requires them to be unique within the same
scope (which is why later assignments replace the previous value
accordingly).

You (still) expect compilers to read your mind which will just not happen
in the foreseeable future.
PointedEars
Jul 23 '05 #8

P: n/a
"Thomas 'PointedEars' Lahn" <Po*********@web.de> wrote in message
news:13****************@PointedEars.de...
VK wrote:
From my amateur look if I do:
hashObject = {VAR_NAME1 : "foo", VAR_NAME2 : "bar"};


First of all, `hashObject' is gibberish. All JS objects could be
considered hashes, whether defined using an object literal or not.


It is not "gibberish". 'hashObject' is the name of a variable that
contains a reference to a J(ava)Script object. As such, it can be any
sequence of characters that constitutes a legal variable name in the
language. While the _concept_ of a hash object may be inappropriate, the
author is completely free to use any sequence of legal characters for
his variable names. As such, it is not "gibberish" anymore than:

var dream = { duration:0.0, lucid:false };

can be "gibberish" because J(ava)Script objects can not be a 'dream'.
Or:

var object = { property_name:value };

is "gibberish" because all J(ava)Script objects are an 'object'.

--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #9

P: n/a


*** Sent via Developersdex http://www.developersdex.com ***
Jul 23 '05 #10

P: n/a
VK
> All JS objects could be
considered hashes, whether defined using an object literal or not.


We're coming back to the same cocktail in many heads that I'm trying to
sort apart for a longest time.

JavaScript by itself has Array and Map Table ("Hash" trigs many people
for some reason) data structures. They are very different by
property/methods and by data handling. If you read samples from:
<http://www.geocities.com/schools_ring/ArrayAndHash.html>
it makes it perfectly clear.

While usung JavaScript to manupilate DOM, the third legacy data
stucture comes into play: HTMLCollection (Collection, Enumerator). This
one has nothing to do neither with array nor with hash. It is a very
specific structure originally made to facilitate as much as possible
the first exeprience of the first LiteScript (-> JavaScript) users.
In HTMLCollection all object and internal collections are originally
sorted by their order in the page layout (from top to bottom). They are
always referred by the ordinal number (stored as a property string!),
and optionally by two more keys: name and id.
At has *nothing* to do in common with any known programming data
structure. It's HTMLCollection and that's it.

A lot of confusion arises I guess from the fact that JavaScript is not
incapsulated language and it does a lot od that we would call in other
place "background casting".
<sample>
var arrayObject = new Array();
alert(arrayObject.slice) // native code
arrayObject = document.getElementsByTagName('P');
alert(arrayObject.slice) // undefined !

So it's not an array acting as collection (or collection acting as
array). JavaScript just makes background casting on the fly:
(Collection)arrayObject = document.getElementsByTagName('P');

Jul 23 '05 #11

P: n/a
VK wrote:
<snip>
While usung JavaScript to manupilate DOM, the third legacy data
stucture comes into play: HTMLCollection (Collection, Enumerator).
The HTMLCollection interface is defined in the W3C HTML DOM
specification.
This one has nothing to do neither with array nor with hash.
No it wouldn't have, it is an interface that may be implemented on a
host object, and so distinct from javascript language defined objects.

<snip> A lot of confusion arises I guess from the fact that JavaScript
is not incapsulated language and it does a lot od that we would
call in other place "background casting".
<sample>
var arrayObject = new Array();
alert(arrayObject.slice) // native code
Javascript arrays have slice methods defined on their prototypes.
arrayObject = document.getElementsByTagName('P');
alert(arrayObject.slice) // undefined !
The getElementsByTagName method is defined as returning an object
implementing the NodeList interface. The NodeList interface defines no
slice method.
So it's not an array acting as collection (or collection
acting as array).
It is two independent objects, defined in different standards but each
having well defined and consistent behaviour.
JavaScript just makes background casting on the fly:
(Collection)arrayObject = document.getElementsByTagName('P');


There is no casting here. The object returned from getElementsByTagName
is required to implement the NodeList interface at minimum, and that is
what it does.

You would confuse yourself less if you would appreciate that ECMA 262
defines a language that is used to script object models, and web
browsers provide those object models. ECMA 262 doesn't have much to say
about what will be provided in those object models, or the behaviour of
the host objects it provides. The W3C defines a document object model
for use in web browsers (and other places) and provides a binding to
ECMAScript for that object model.

Javascript never casts objects. The language itself only uses one type
of object, and that object is totally dynamic so any object may
implement any interface, and different interfaces at different times. No
casting of objects is necessary (or meaningful) under those
circumstances. Host objects (those provided by the object model being
scripted) do not have to be dynamic, but javascript still does not
regard them as being of distinct types. The host object has the
interface it has, and javascript can use whatever it provides without
regard for where those facilities specifically originate. Thinking in
terms of 'casting' in a language that does not have classes is likely to
be counterproductive.

Richard.
Jul 23 '05 #12

P: n/a
VK
> > <sample>
var arrayObject = new Array();
alert(arrayObject.slice) // native code
arrayObject = document.getElementsByTagName('P');
alert(arrayObject.slice) // undefined !
The getElementsByTagName method is defined as returning an object
implementing the NodeList interface. The NodeList interface defines no
slice method.


Exactly my point. As getElementsByTagName() returns an HTMLCollection,
JavaScript automatically converts arrayObject from Array type to
HTMLCollection type to accomodate new data structure. (You can easy
observe it by checking method/properties "before" and "after"). So it
is effectively switching interfaces for data, and this is what actually
"casting" is. Simply in typed languages casting doesn't happen "by
itself", so I call it "background casting".
Overall it's the same as

var myVar = 1; // see what methods you can apply here
myVar = "Hello world!"; // here
myVar = true; // and here
// etc.
Javascript never casts objects. myObject.toString();
The most primitive type of explicit casting I'm sure you used a while
already.
The language itself only uses one type
of object, and that object is totally dynamic so any object may
implement any interface, and different interfaces at different times.
This description fits to any existing OOP language.
The main specifics of JavaScript that it doesn't incapsulate objects
(as well as primitive data types), so any second they are ready to be
whatever you're pushing on them from the right side of the assignement.
You give them collection - it will become HTMLCollection, Array - so be
array, number - so the better. But until the next "transformation" (if
you don't like the term "casting") they are particular objects with
particular property/methods (added right to the instance, native,
inherited or prototyped).
Thinking in
terms of 'casting' in a language that does not have classes is likely to
be counterproductive.


Class is simply a factory of objects with predefined behaviors.
Each object in JavaScript has its constructor property reffering to its
creator. To avoid the word "class" we could call it "object
constructor" but it would be a bizarre term. Just say it: "class
constructor", and you will feel a gread relieve in your mind ;-)

Jul 23 '05 #13

P: n/a
VK wrote:

Who wrote that? Please provide proper attribution.
vvvvvvvvvvvvvvv
> <sample>
> var arrayObject = new Array();
> alert(arrayObject.slice) // native code
> arrayObject = document.getElementsByTagName('P');
> alert(arrayObject.slice) // undefined !
The getElementsByTagName method is defined as returning an object
implementing the NodeList interface. The NodeList interface defines no
slice method.


Exactly my point. As getElementsByTagName() returns an HTMLCollection,
JavaScript automatically converts arrayObject from Array type to
HTMLCollection type to accomodate new data structure.


No, "it" does no such thing at all. What happens is that the reference to
the newly created Array object that is stored in the `arrayObject' variable
is replaced by a reference to the HTMLCollection object that the W3C DOM
method returns. Since the HTMLCollection interface does not provide a
`slice' method, of course `arrayObject.slice' yields `undefined' as the
object referred to does not have such a method. (Richard already explained
that to you.) See ECMAScript 3, subsection 11.13.1.

It is then likely, if there are no further references to the Array object,
that the Garbage Collector will mark the unreferenced Array object for
deletion, and therefore the memory allocated for that object will
eventually be freed.
Javascript never casts objects.

myObject.toString();
The most primitive type of explicit casting I'm sure you used a while
already.


myObject.toString() performs implicit type conversion of `myObject' by
returning a string value; for non-core objects, the `toString()' method
inherited from the Object prototype may be redefined to accomodate the
features of the calling object. This is *not* the same as type casting
as implemented in class-based OOP languages like Java. See ECMAScript 3,
subsections 15.2.4.2, 15.3.4.2, 15.4.4.2, 15.5.4.2, 15.6.4.2, 15.7.4.2,
15.9.5.2, 15.10.6.2 and 15.11.4.4, and e.g.
<http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.5>
The language itself only uses one type of object, and that object is
totally dynamic so any object may implement any interface, and different
interfaces at different times.


This description fits to any existing OOP language.


No it does not. E.g. classes in Java are of different data types:
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3>
Thinking in terms of 'casting' in a language that does not have classes
is likely to be counterproductive.


Class is simply a factory of objects with predefined behaviors.
Each object in JavaScript has its constructor property reffering
to its creator.


There was not even a `constructor' property defined before JavaScript
1.1, JScript 2.0 and ECMAScript although JS was object-oriented and had
constructors from the start. And the `constructor' property is not
read-only.
To avoid the word "class" we could call it "object
constructor" but it would be a bizarre term.


No. In JavaScript 1.x/JScript up to 5.x/ECMAScript up to 3, objects
inherit from each other. In Java and other class-based OOP languages,
classes inherit from each other and an object is an instance of a class.
PointedEars
Jul 23 '05 #14

P: n/a
VK wrote:
> <sample>
> var arrayObject = new Array();
> alert(arrayObject.slice) // native code
> arrayObject = document.getElementsByTagName('P');
> alert(arrayObject.slice) // undefined !
The getElementsByTagName method is defined as returning
an object implementing the NodeList interface. The NodeList
interface defines no slice method.


Exactly my point. As getElementsByTagName() returns an
HTMLCollection,


The getElementsByTagName method is specified as returning a _NodeList_
not an HTMLCollection. It is a Core DOM method and apples to non-HTML
documents in addition to HTML documents. (Granted if you have a host
object for interaction with JS that implements HTMLCollection there is
no reason not to use that same object when a NodeList is called for as
HTMLColleciton implements all of the NodeList interface).
JavaScript automatically converts arrayObject from Array
type to HTMLCollection type to accomodate new data structure.
(You can easy observe it by checking method/properties "before"
and "after").
It took me a while but I finally worked out which misconception had
resulted in this nonsense.

You are thinking of - arrayObject - as, in some sense, having a type.

In javascript all variables are in reality properties of objects. Global
variables are properties of the global object, so in the code above the
variable 'arrayObject' is a property of the global object named
'arrayObject'. Properties of objects that exist have values and an
assignment operation assigns a value to a property. The properties
themselves have no 'type', only a value. The value assigned to a
property will have a type, and can be of any type defined in the
language (though that just means one of: Undefined, Null, Boolean,
Number, String or Object (ECMA 262 3rd edition section 4.3), as that is
all of the types that can be explicitly assigned to property values).

Following:-

var arrayObject = new Array();

The property of the global object 'arrayObject' refers to an instance of
a javascript Array. But the assignment:-

arrayObject = document.getElementsByTagName('P');

- does not change the type of 'arrayObject' it changes its value into a
reference to an object implementing the NodeList interface.

And the Array object that was originally assigned to 'arrayObject' is
not changed in any way by the subsequent assignment (except that if it
is no longer referred to by any object properties it may be garbage
collected).
So it is effectively switching interfaces for data,
and this is what actually "casting" is.
So you are defining 'casting' as changing the value of an object's
property from a reference to object A into a reference to object B?
Simply in typed languages casting doesn't
happen "by itself", so I call it "background casting".
Overall it's the same as

var myVar = 1; // see what methods you can apply here
Assigning a numeric value to a property of the global object.
myVar = "Hello world!"; // here
Then assigning a string value to that same property.
myVar = true; // and here
And finally assigning a boolean value. No casting there, not even any
type-conversion.

In a strongly typed language a variable (and/or an object member) must
be declared as some type. As a result it would not be legal to assign a
sequence of value of the 'wrong' type. That just doesn't apply to
javascript.
// etc.
Javascript never casts objects. myObject.toString();
The most primitive type of explicit casting I'm sure you used a while
already.


I was talking in terms of casting objects into different types, in the
way that in Java you may cast an object into the 'type' of an interface
that it implements. As javascript treats all objects as being the same
type there are no other types to cast them to.

You can type-convert, including converting an object into a string
primitive, which is done by implicitly or explicitly calling its
toString method (and may error if the object is a host object taking
advantage of the provision for it not to implement a toString method).
Type-conversion only takes place between javascript's defined types:
Undefined, Null, Boolean, Number, String or Object. Object is the only
object type but can be type-converted to any primitive type except
Undefined and Null. It is also not possible to type-convert any other
primitive to Undefined or Null. Undefined and Null may be type-converted
to any other primitive type but cannot themselves be type-converted into
objects, unlike the other primitive types.
The language itself only uses one type of object,
and that object is totally dynamic so any object may
implement any interface, and different interfaces at
different times.


This description fits to any existing OOP language.


The same object can implement different interfaces at different times?
That is exactly the type of behaviour that strong typing prevents. Now,
one object (in, for example, Java) may implement several interfaces, but
that object will implement all of those interfaces at all times.
The main specifics of JavaScript that it doesn't
incapsulate objects (as well as primitive data types),
so any second they are ready to be whatever you're
pushing on them from the right side of the
assignement.
This seems your main misconception here. The thing to the left in an
assignment has no concept of 'type' at all. It is just a slot into which
a value may be placed. Any value of any type. In class based languages
those slots may be qualified as only accepting a single type, but
javascript is loosely typed and is not class-based.

But your misconception should become obvious to you when you consider
that you wrote:-

| (Collection)arrayObject = document.getElementsByTagName('P');

- with its implication that you would cast the left hand side of an
assignment in (I assume) Java. You would not, the left hand side is
fixed when it is declared, it is the right hand side you would be
casting, if at all.
You give them collection - it will become
HTMLCollection, Array - so be array, number - so the
better. But until the next "transformation" (if you don't
like the term "casting") they are particular objects with
particular property/methods (added right to the instance,
native, inherited or prototyped).
Consider:-

var a = new Array();

var b = a; // b now refers to the same array as a

var c = a; // c now refers to the same array as a

c = 'any string';

- you would be implying that the act of assigning a string literal to c
would in some sense 'transform' the object that it previously referred
to (the Array object that was originally assigned to a and is still
referred to by a and b). Try it, you will not find any evidence of any
transformation in the Array, and it certainly has not changed into a
string.
Thinking in terms of 'casting' in a language
that does not have classes is likely to be
counterproductive.


Class is simply a factory of objects with predefined
behaviors.


But the behaviour of dynamic objects is not fixed, so not defined, so
not pre-defined.
Each object in JavaScript has its constructor property
reffering to its creator.
Having the same creator does not imply having the same behaviour,
structure or properties. in javascript.

function MyObject(){
}

var a = new MyObject();

MyObject.prototype = {type:'I am one type'};

var b = new MyObject();

MyObject.prototype = {className:'I am different'};

var c = new MyObject();

alert(a.type); // 'undefined'
alert(b.type); // 'I am one type'
alert(c.type); // 'undefined'

alert(a.className); // 'undefined'
alert(b.className); // 'undefined'
alert(c.className); // 'I am different'

alert(a.constructor == b.constructor); // 'false'
alert(b.constructor == c.constructor); // 'true'
alert(a.constructor == c.constructor); // 'false'

alert(a.constructor == MyObject); // 'true'
alert(b.constructor == MyObject); // 'false'
alert(c.constructor == MyObject); // 'false'

- One constructor function, three distinct object 'types', only two of
them share the same 'constructor' property and that is not a reference
to the function that constructed them.

Or:-

function MyObject_1(){
}
function MyObject_2(){
}
MyObject_2.prototype = MyObject_1.prototype;

var a = new MyObject_1();
var b = new MyObject_2();

alert(a.constructor == b.constructor); // 'true'

- Two different constructor functions, creating identical objects that
even think they have the same constructor.
To avoid the word "class" we could call it "object
constructor" but it would be a bizarre term.
And an utterly futile suggestion given the loose relationship between
constructor functions and the objects they construct.
Just say it: "class constructor",
and you will feel a gread relieve in your mind ;-)


No, I will continue to think of javascript as the class-less language
that it is. And reserve the term class for the sub-set of object
implementations that are designed to be approximately analogous in their
definition _and_ employment with classes in class-based languages.
Terminology that I shall use only when doing so is appropriate an
advantageous, and without letting it get in the way of my appreciation
of what javascript really is: loosely typed, class-less and dynamic.

Richard.
Jul 23 '05 #15

P: n/a
"VK" <sc**********@yahoo.com> writes:
JavaScript by itself has Array and Map Table ("Hash" trigs many people
for some reason) data structures.


I think I have finally found out what is bothering me with this
representation.

Let's agree that arrays are an abstraction, and that "array elements"
are defined by the abstraction without needing to exist in the
underlying object used to implementat the array. That is, the object
with the updating "length" property is an array because that is its
intention, its preferred interpretation.

This is, I believe, your view as well, right?

My problem comes when you start referring to objects as if their
intent was to act as an associative array (or map or hash or whatever
they are called in different language settings).

Objects do map property names to property values, as in other OO
languages. The difference between Java and Javascript is (among other
things) that you can update the set of properties of an object
at runtime, adding, changing and deleting properties.

That means that the object can be *used* as an updatable map from
names to values. That is not its intention, though. It is still
intended as an *object*. It also makes a non-perfect implementation
of an associative array, since it doesn't start out empty.

So, my point is that Javascript doesn't have associative arrays built
in. It has mutable objects. If you break the abstraction and look at
objects as only associative arrays, ignoring that that is not what
they mean, you should do the same to arrays and see them as only
objects with a "magical" length property..

If you want to implement an associative array using an object, you
can do something like:

---
function AssociativeArray() {
this.elements = {};
}
AssociativeArray.prototype.put = function put(keyString, value) {
this.elements[keyString] = value;
}
AssociativeArray.prototype.containsKey = function(keyString) {
return this.elements.hasOwnProperty(keyString);
}
AssociativeArray.prototype.get = function get(keyString) {
return (this.containsKey(keyString))
? this.elements[keyString]
: null;
}
AssociativeArray.prototype.remove = function remove(keyString) {
if (this.containsKey(keyString)) {
delete this.elements[keyString];
}
}
---

This abstraction implements an associative array that is initially
empty.


/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 #16

P: n/a
rh
Lasse Reichstein Nielsen wrote:
"VK" <sc**********@yahoo.com> writes:
JavaScript by itself has Array and Map Table ("Hash" trigs many people
for some reason) data structures.
I think I have finally found out what is bothering me with this
representation.

[...]
So, my point is that Javascript doesn't have associative arrays built
in.


Ah but, being initially non-empty doesn't remove the ability to
characterize a basic object as an associative array. Otherwise, to
state the obvious, an associative array -add- operation would cause an
associative array to cease to be an associative array.

In order to fail to be able to characterize a basic object as an
associative array, a more rigorous definition of associative array
would have to be used than is normally encountered. That would include
specification of an initial state as being empty, and that the
associative array can be modified only by direct operations on the
object (since modification of an object in the prototype chain can
indirectly modify the content of the "associative array" object).

Then I could more readily accept your point.

Nonetheless, I think it's very useful to think of Javascript objects in
terms of associative arrays, as that's what constitutes their
fundamental construction. The prototype chain simply links a set of
associative arrays together, thereby creating a Javascript object.

With an understanding of that model, it's relatively easy to move on to
the higher level notion of "intent" of a Javascript object,
particularly because the concept of prototype inheritance easily
follows, and much of the grand mystery surrounding what objects are is
removed.

[...]

../rh

Jul 23 '05 #17

This discussion thread is closed

Replies have been disabled for this discussion.