<FAQENTRY> Array and hash (associative array)

M

Michael Winter

OK
JavaScript array is not really an array.

That probably depends on the definition that you want to use. The
definition that I'm accustomed to is a homogeneous collection of
elements located sequentially in memory. However, more generic
definitions are just as acceptable.

What arrays in ECMAScript certainly are, are Object objects with
specialised behaviour. The same can be said for any native object.
arrayObject.length keeps the highest index you managed to use so far.

The highest plus one.
It has *no* connection with the actual array's length, it's just called
so for further convenience.

I disagree. The array:

[, 1]

has two elements, and a length of two. Just because the first element is
undefined doesn't make the size any smaller. If you think it should,
then you are probably using the wrong data type.

[snip]
Could we at least to mention in the FAQ's, that despite array and
associative array (map, collection, hash table) is the same thing in
JavaScript

OK, how many times does this need to be said: an array is not an
associative array, and an object is not an associative array. That might
be how they are implemented, and that's the sort of behaviour they
appear to possess, but that doesn't change the reality of the situation.
if you do arrayObject[SomeNumber] = someValue, it counts it in
arrayObject.length

If SomeNumber is a 32-bit unsigned integer, yes.
It also lets you to use standard array methods on this member. (1st
category)

The Array prototype methods generally operate in the range of named
properties [0, length), so that much is obvious. Some work outside that
range, namely when extending the number of elements.
if you do arrayObject[SomeString] = someValue, the engine doesn't it in
arrayObject.length

If SomeString represents an array index, then that assignment certainly
does affect the length. If SomeString is not an array index, then of
course it won't affect the length.
and you cannot use standard array methods on this member. (2nd
category)

For the previously cited reason.
Until JavaScript/JScript engine producer will rectify this obvious bug,

It is not a bug. It is clearly defined behaviour.
you need to be very attentive while putting new members in your
arrayObject. [...]

One merely needs to understand the language. You clearly don't. I
suggest you get yourself a copy of ECMA-262 and read items 15.4 and
15.4.5.1, and compare the latter to 8.6.2.2.

Mike
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Sun, 19 Jun 2005
18:09:37, seen in Lasse Reichstein Nielsen
You can do that, and most of the time it will work fine for
you. However, there will be the odd case where understanding how
arrays work, in particular that the length property only guarantees
to be at least one larger than the highest array index in use, is ^ integer ?
necessary.


The prime point is the one I made before; that the length property does
not in the general case reflect the total number of elements, but is
associated with the number of non-negative-integer-index elements.

It is in fact associated with the way in which arrays work in Algol,
Pascal, and I presume C; and arrays in javascript are often used in that
manner, with integer indexing.

Once that is understood, it will sometimes be necessary to go into the
matter further.
 
L

Lasse Reichstein Nielsen

Michael Winter said:
I disagree. The array:

[, 1]

has two elements, and a length of two.

I can see why Mr. VK gets confuzed, because I would say that this
array has one element and a length of two. It matters (to me) that
the array doesn't have a property called "0".

But then again, as Mr. VK also said, if I understood the Java
comparison correctly, arrays in Javascript is an abstraction on top of
an object. If you keep within the abstraction, you can treat the array
as having two elements. If you break the abstraction and uses the
array as a general object, then you need to know the implementation.

Safer languages protects their abstractions, Javascript is not one :)
OK, how many times does this need to be said: an array is not an
associative array, and an object is not an associative array. That
might be how they are implemented, and that's the sort of behaviour
they appear to possess, but that doesn't change the reality of the
situation.

<devil's advocate>
What property of an associative array does an object fail to
match?
It is not a bug. It is clearly defined behaviour.

Hear, hear.
I can't even see what the bug should be, except the failure to protect
the abstraction that is an array from its implementation.

/L
 
R

Richard Cornford

Lasse Reichstein Nielsen wrote:
Safer languages protects their abstractions, Javascript
is not one :)

So let's not pretend it is safe, because it will turn and bite those who
assume it is.

<devil's advocate>
What property of an associative array does an object
fail to match?
</devil's advocate>
<snip>

The common expectation of an "associative array" seems to be that the
number of key/value pairs assigned will be reflected in a - length -
property. Hence the disappointment when javascript does no such thing.

Richard.
 
M

Michael Winter

JRS: In article <[email protected]>, dated Sun, 19 Jun 2005
18:09:37, seen in Lasse Reichstein Nielsen
[...] the length property only guarantees to be at least one larger
than the highest array index in use [...]

^ integer ?

Array indicies are a subset of object property names, and are only
defined in terms of 32-bit unsigned integers, so it would seem redundant.

[snip]

Could I ask a small favour of you, John? Can you check if IE4 supports
String.prototype.charCodeAt? Microsoft's documentation says it doesn't,
but my copy does. Though it is running on XP, it has a separate
jscript.dll library and should be independent from the system libraries.
It is with regard to other methods like Array.prototype.push.

Mike
 
M

Michael Winter

Michael Winter said:
I disagree. The array:

[, 1]

has two elements, and a length of two.

[...] I would say that this array has one element and a length of two.

Whilst I still disagree, I do find it somewhat difficult to put into
words why. Perhaps it's my definition of what an array is, and why they
are normally used; a consequence of the notion of continuity, even if
the array is sparse.
It matters (to me) that the array doesn't have a property called "0".

Although I understand that the property '0' doesn't exist in that

[, 1].hasOwnProperty('0')

returns false (interestingly, Firefox returns true), it still does have
a 0th element. It is a zero-indexed array, sparse or otherwise, so it
must have all of the elements in the range [0, length).

[snip]
<devil's advocate>
What property of an associative array does an object fail to
match?
</devil's advocate>

rf answered this one a while ago. In most ways, native objects do
resemble associative arrays. They possess both put and get operations,
and indicies are not limited to just numbers. However, a native object
is never empty. This renders get operations vulnerable to cases where a
prototyped property is returned as an element, which could include
arbitrary properties introduced by user code.

Though this problem could be mitigated by user code, the associative
array is now a user object, and not a native object.

[Regarding non-array index properties not affecting length]
I can't even see what the bug should be [...]

I didn't mean for the summary about to answer the question, but that's
my understanding of it.

Mike


Does the subject of this thread need to be changed so that each post
isn't flagged as a potential FAQ entry?
 
L

Lasse Reichstein Nielsen

Michael Winter said:
It is a zero-indexed array, sparse or otherwise, so it must have all
of the elements in the range [0, length).

So this is what it boils down to :)
Should a sparse datastructure be considered to have elements even
where they are not specified? I say no :)
However, a native object is never empty. This renders get operations
vulnerable to cases where a prototyped property is returned as an
element, which could include arbitrary properties introduced by user
code.

So the property it fails to have is the ability to be empty.
That's good enough for me :)

/L
 
V

VK

Does the subject of this thread need to be changed
so that each post isn't flagged as a potential FAQ entry?

Maybe, but how to call this new thread? Actually it's asking for
another
<FAQENTRY> title like "Does the world really exist or it's given to me
in my sensations and experience only?"

I don't really understant this attempt to alienate JavaScript
from any other language as it was written on Mars. It has the
most of the same entities as any other programming environment.

Any programming language is an abstraction. There is only two
real things: loaded/unloaded (1/0) memory cells and processor
flags after reading these cells. From this point of view there
is only one *real* language: ASSEMBLER (w/o mnemonics of course
as a disturbtion of the purity of the picture). Anything atope
of it as a *human abstraction* to desribe the movement and
allocation of these loads in the cells. There are not any objects,
arrays, hashes, variables etc. All from above is a kind of
"public agreement" in the meaning of Plato and Aristotle.
Nothing could us stop from deciding that say "array" would be
a data conglomerate where every second item starts with "A"
(or something even more bizzare).
On the OOP level any language consists of a set of objects,
where each object inherits/overloads/adds some method/properties
to the original Object (the Father of Gods). I don't see here
any major difference from any language. You can create a Data()
object in JavaScript and use it to play your media clips. You can
create a Array() object in JavaScript and use it to hold your
hash table. (Both by extending its properties or by changing
its prototype). Do you think that JavaScript is the most flexible
here? Some languages support operator's overload. So if you are
really bored at some sleepless night, you can make "+" sign to act
as "-" and vice versa. But do we need to state that Java
(that supports it) doesn't have a "+" sign but some "math object"
acting upon how do you use it?
If we stay at this point of view then there is no any fixed object,
and we're always acting with "something that can be anything" and the
only truth may come from our runtime experience. That puts us into
the most low level of the idealisme subjectif bordering with
a pure sensualisme.

IMHO You should respect profoundly the "public agreements"
about array and hash table (map, collection).
Otherwise you're the person who doesn't pay his bills on time
(because you're benefiting of something created 'cause of a public
agreement, but you don't want to follow that agreement right after).

In the particular, if you do var arrayObject = new Array();
you have to treat arrayObject as an array exclusively.
Otherwise why the hell did you create it?
 
J

John G Harris

In the particular, if you do var arrayObject = new Array();
you have to treat arrayObject as an array exclusively.
Otherwise why the hell did you create it?

Is that what you're trying to say : don't misuse Array objects; if you
do you'll get into trouble. I wish you'd learn to say it more clearly.

John
 
J

John G Harris

On the OOP level any language consists of a set of objects,
where each object inherits/overloads/adds some method/properties
to the original Object (the Father of Gods).
<snip>

C++ doesn't have an 'original object' type, and is all the better for
it.

John
 
D

Dr John Stockton

JRS: In article <[email protected]>,
dated Sun, 19 Jun 2005 22:59:29, seen in
Michael Winter said:
JRS: In article <[email protected]>, dated Sun, 19 Jun 2005
18:09:37, seen in Lasse Reichstein Nielsen
[...] the length property only guarantees to be at least one larger
than the highest array index in use [...]

^ integer ?

Array indicies are a subset of object property names, and are only
defined in terms of 32-bit unsigned integers, so it would seem redundant.


Commonly, that which is used in conjunction with an array name to
indicate a specific element of an array will be considered, rightly or
wrongly, to be an array index; so ISTM useful to include an adjective as
a reminder even if it is in truth superfluous.

BTW, I should have included non-negative; good languages can allow
negative indexes.


Could I ask a small favour of you, John? Can you check if IE4 supports
String.prototype.charCodeAt? Microsoft's documentation says it doesn't,
but my copy does. Though it is running on XP, it has a separate
jscript.dll library and should be independent from the system libraries.
It is with regard to other methods like Array.prototype.push.

Not sure what you mean there.

"qwertyuiop".charCodeAt(5)

has the value 121, matching "y" and
"qwer\u0646yuiop".charCodeAt(5) -> 121
"qwer\u0646yuiop".charCodeAt(4) -> 1606 d wok / dt

Otherwise, if you send test code I'll try it.
 
R

Richard Cornford

VK wrote:
I don't really understant this attempt to alienate JavaScript
from any other language as it was written on Mars. It has the
most of the same entities as any other programming environment.
<snip>

There isn't an attempt to alienate javascript from other languages.
There is an attempt to understand what javascript is. It is very useful
to understand what javascript is if you are going to program it, and not
particularly helpful to know what VBScritp is.

There are certainly plenty of things that are very similar in any
programming language. A while loop is much the same everywhere, and
recognisable as a while loop even in assembly language. But the aspects
of any language that need most effort to appreciate are the aspects that
make it distinct from other languages. And in many respects javascript
is very distinct, and its closest relatives are not Java and C++,
regardless of syntactic similarities.

However, it is in the nature of javascript that if you can recognise a
concept in any other language you can implement it in javascript. So,
conceptually, you can have a class hierarchy, private object members,
multiple inheritance, and anything else you can think of from a class
based language. Not because these things are part of javascript but
because they can be created with javascript.

The problem being that while you can design and create javascript with
concepts borrowed from class-based languages you cannot do so without
understanding javascript, and you cannot understand javascript in terms
of the concepts from class-based languages (not even its OO aspects).

In the end the value of the approach you take towards understanding a
programming language can be judged by how effective it is. You have
spent the last couple of months posting absolute twaddle about event
handlers, and disregarding the various corrections and suggestions you
have been offered along the way. But when it came down to it Mike Winter
knew how to meet the challenge you set him with _one_line_of_code_. He
has known how to do that for some considerable time, and he attempted to
explain it to you in detail at lest twice.

Under the circumstances you have to wonder why you winged-on about
browser bugs and "this is that" for a couple of months while surrounded
by scores of individuals who self evidently were having no problems
employing event handlers. The obvious conclusion is that the conceptual
model that you use to understand javascript is fatally flawed. That it
is that that gets in the way of you understanding whet you are
attempting.

There is not much point in arguing that javascript may be understood in
the particular way that you are comfortable with when in your case that
style of conception is so evidently ineffective, and the people you are
arguing with are the ones that understand javascript (and don't spend
months going round in circles), and so have learnt how it can be best
understood.

Much better to take that advice you have been given and start to learn
the language you are using.

Richard.
 
M

Michael Winter

On 20/06/2005 20:32, Dr John Stockton wrote:

[snip]
BTW, I should have included non-negative; good languages can allow
negative indexes.

To address memory locations prior to element 0? Languages that actually
implement arrays in the traditional sense could do that, or course, but
one could hardly expect ECMAScript to allow that.

[snip]
Not sure what you mean there.

"qwertyuiop".charCodeAt(5)

has the value 121, matching "y" [...]

That's what I meant, though I should have asked if you are running IE4
with its original JScript implementation, or have you upgraded that
separately?

As I said, Microsoft's documentation states that
String.prototype.charCodeAt is implemented as of JScript 5.5, but the
IE4 I'm running uses an earlier version and still implements the method.
I was wondering if that was somehow a product of running on XP (which I
doubt), or if the documentation is wrong.

Thank you,
Mike
 
V

VK

To finalize (read <APPENDIX> at the bottom if more interested)

To stop this <FAQENTRY> from flaggering like a hell's gates counter,
I'm proposing a UN Counsil style text (no politics discussions, only
fully mutually acceptable points).

<FAQENTRY>
<QUE>
I'm doing:

var myObject = new Array();
var myObject["StringIdentifier"] = IdentifierValue;

But myObject.length doesn't change. What a hay? I event tried:

var myObject = new Object();
var myObject["StringIdentifier"] = IdentifierValue;

but it doesn't help!
</QUE>
<ANS>
The myObject.length property is set properly
only for an array which you have declared
by using var myObject = new Array() or by
var myObject = [item1, item2, item3]
and only if you're using positive integers for identifiers.
If some of your identifiers are strings, they will not be counted
to the myObject.length. In the particular, all form values come
to the function as strings. So even if your textField.value contains
a number, it will be treated as a string. So to ensure that
myObject.length
is set properly, you should do at the least:
var myObject[+Identifier] = IdentifierValue;
</FAQENTRY>

I think that now it's up to the group moderator to decide is this FAQ
is F (frequent) enough to include it into the list. (my opinion is
"YES", but it's only my IMHO). Upon his positive decision we could
bring it to a totally mutually acceptable form.

<APPENDIX>
So you think that var mapObject = {}; and var arrayObject = []; do the
same ?

You think that ability to link a proprietary amount of indexes (=>
dimentions) to a single value doesn't differ anyhow an array from a
hash table (where on has hard key/value links) ?

You think that the "random" order the key/value pairs are allocated in
memory baskets doesn't differ from the strict index based order of
array elements ?

Fine by me.

I'm going eazy with it now supported by two good proverbs:

(1) An old Persian one:
"Who can stop Hafiz from liken a ladybug to The Padishah?"
(means you can compare anything with anything as long as you see a
reason for it).

(2) The one came from modern China:
"It is no matter what color is the cat as long as it still hounts the
mice."
(means as long it works, it's fine)
</APPENDIX>
 
V

VK

Did you ever program using C++ or you're just sharing with the
community some terrible hightmares you had recently? Did you see a
deriving classe there or it was swalowed by a fire-breathing dragon?

Dr. VK
 
V

VK

C++ doesn't have an 'original object' type,
and is all the better for it.

My previous reply on your post was on the level of a profanity.
I'm sorry in front of you, it's not my style really.
Yes, in C++ you're protected on the level of the language
promitives at least. (so array is always an array for you,
leaving the operators' overloading "leak" though). But
would you like to see a requirement to treat your class B
exactly as class A just because your class B was
derived from class A ??
 
L

Lasse Reichstein Nielsen

The myObject.length property is set properly
only for an array which you have declared
by using var myObject = new Array() or by
var myObject = [item1, item2, item3]

That is, for an array, no matter how it is instantiated (not
"declared").
and only if you're using positive integers for identifiers.

(within the range 0..2^32-2)
If some of your identifiers are strings, they will not be counted
to the myObject.length.

Incorrect. The parameter of the square bracket notation is always
converted to a string. If that string is a 32 bit integer in canonical
form (i.e., a valid array index), then assigning might change the
length property of the array. (Canonical form here means no initial
zeros, decimal point or exponential notation, so "1" is an array index
while "01", "1.0" and "1E+0" are not).
In the particular, all form values come
to the function as strings.

What function? The value property of form controls are strings.
So even if your textField.value contains
a number, it will be treated as a string. So to ensure that
myObject.length
is set properly, you should do at the least:
var myObject[+Identifier] = IdentifierValue;

Not necessary if the string is the canonical representation of an
appropriate integer.


/L
 
D

Dr John Stockton

JRS: In article <[email protected]>,
dated Tue, 21 Jun 2005 10:56:25, seen in
Michael Winter said:
On 20/06/2005 20:32, Dr John Stockton wrote:

[snip]
BTW, I should have included non-negative; good languages can allow
negative indexes.

To address memory locations prior to element 0? Languages that actually
implement arrays in the traditional sense could do that, or course, but
one could hardly expect ECMAScript to allow that.

I don't see why not, except on the basis of the language having been
written in a country that never developed its own natural language.
In Pascal/Delphi, array indexes are given upper and lower bounds, and
indexing can be by any ordinal type (i.e. boolean, enumerated, or any
variety of integer except comp and maybe Int64 (IIRC)).

"qwertyuiop".charCodeAt(5)

has the value 121, matching "y" [...]

That's what I meant, though I should have asked if you are running IE4
with its original JScript implementation, or have you upgraded that
separately?

Original; had I changed it, I'd probably have remembered to say.
 
D

Dr John Stockton

JRS: In article <[email protected]>
, dated Tue, 21 Jun 2005 10:36:48, seen in VK
Did you ever program using C++ or you're just sharing with the
community some terrible hightmares you had recently? Did you see a
deriving classe there or it was swalowed by a fire-breathing dragon?


<FAQENTRY>
If you find that, when you start a News reply, Google does not provide
the previous article in quoted form, note what Keith Thompson wrote in
comp.lang.c, message ID <[email protected]> :-
If you want to post a followup via groups.google.com, don't use
the "Reply" link at the bottom of the article. Click on "show
options" at the top of the article, then click on the "Reply" at
the bottom of the article headers.
 
M

Michael Winter

On 21/06/2005 20:54, Dr John Stockton wrote:

[JRS:]
[...] good languages can allow negative [array] indexes.
[MLW:]
[...] one could hardly expect ECMAScript to allow that.

I don't see why not [...]

At face value, negative indices have value in languages that use pointer
arithmetic to address array elements. However, an ECMAScript
implementation is more likely to use a map to implement arrays.
In Pascal/Delphi, array indexes are given upper and lower bounds [...]

I'm unfamiliar with Pascal (though it's usually readable), so I can't
comment in any detail, but I would expect those arrays to be created
normally, but any index would be offset automatically to address the
array normally. A compiled language could optimise such operations to
the point of removing them altogether, but not a purely interpreted
language.

As this feature can be emulated trivially by a programmer, it doesn't
appear in many languages so there's no impetus to add it to ECMAScript,
either.

[snip]

In all, I don't particularly see the value.

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top