Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > <FAQENTRY> Array and hash (associative array)

Reply
Thread Tools

<FAQENTRY> Array and hash (associative array)

 
 
Richard Cornford
Guest
Posts: n/a
 
      06-19-2005
VK wrote:
>> Why the word 'hash'

>
> To get out of the term "associative array" which:
> 1) confusing ("integer with a floating part" for float
> number - we don't say it, do we?)
> 2) too long to type and to pronounce. It's asking to be
> abbreviated back to "array" like "you know what kind of
> array I'm talking about".
>
> Hash is used as a programming term and entity in Perl, so
> it's not my invention.


"Hash" would be as wrong a term to apply as "associative array". It does
have a use as a programming term and it means something specific. And
that specific something has nothing to do with any of the specified
behaviour of objects in javascript (even if the implementation _may_ be
using HashTables/Maps as the representation of those objects).

All native ECMAScript objects (Objects, Arrays, Functions, Regular
Expressions, prototypes, etc, etc) allow arbitrarily named properties to
be added to them at run-time. It doesn't need the application of a
borrowed term, that is just what any ECMAScript object _is_.

Richard.


 
Reply With Quote
 
 
 
 
Richard Cornford
Guest
Posts: n/a
 
      06-19-2005
VK wrote:
>> Its length now is 1001

> It must be an influence of the Arabian nights stories and
> beer (the latter is more probable)
>
> After having polished my math and brains, my post should be:


Apparently sober your maths are worse.

> ---------------------------------------------------------------------
> It is not theoretically correct. We're having again a simplification
> in
>
> the JavaScript mechnics. The things you have to do explicitly in say
> Java or C++, they are being done here automatically on the background.
>
> If I do something like:
>
> var arr = new Array();
> arr[1000] = 1;
>
> I indeed *resize* the array to hold 1000 new elements.
> Its length now is 1000,


1001

> it contains 1000 elements


1001 (unless you mean it contains 1000 elements equal to undefined, from
index 0 to 999).

> where arr[0] to arr[998] eq *undefined*,


arr[0] to arr[998]

> and arr[999] eq 1


arr[1000] == 1, arr[999] is one of the elements that was never assigned
a value.

> Yes, unternally JavaScript doesn't keep 999 undefined
> values. Only arr[999] value really exists,


arr[1000]

> undefined will be generated
> automatically then addressing an element.
> But this internal mechanics
> is really not of interest of the end-users.

<snip>

What exactly is an "end-user" of javascript? Surly the only sense in
which people use javascript is as a programming language (as a
programming language is the only thing that javascript is). And
javascript programmers absolutely do, and should, need to understand the
technical details of the behaviour of the language that they are using.

Without that understanding they will just find themselves wasting their
time thrashing about in the dark, attributing phenomena they observe but
don't understand to 'browser bugs' and other mystical explanations, and
achieving little of use or value to others.

Richard.


 
Reply With Quote
 
 
 
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      06-19-2005
"VK" <(E-Mail Removed)> writes:

>> Its length now is 1001

....
> After having polished my math and brains, my post should be:
>
> ---------------------------------------------------------------------
> It is not theoretically correct. We're having again a simplification in
>
> the JavaScript mechnics. The things you have to do explicitly in say
> Java or C++, they are being done here automatically on the background.
>
> If I do something like:
>
> var arr = new Array();
> arr[1000] = 1;
>
> I indeed *resize* the array to hold 1000 new elements. Its length now
> is 1000, it contains 1000 elements where arr[0] to arr[998] eq
> *undefined*, and arr[999] eq 1


Actually, the length property does have the value 1001, and it's
arr[1000] that equals 1.

Also, It's, pedantically, incorrect to say that the array holds 1000
(or 1001) elements. It holds exactly one enumerable property (1000), as
can be seen from:

var cnt = 0;
for (var i in arr) {
cnt ++;
}
alert(cnt); // alerts "1".

Try this to see the difference:

var arr = [];
arr[1000] = 1;
arr[500] = undefined;
// above loop gives 2, not 1
alert("500" in arr); // true
alert("501" in arr); // false

> Yes, unternally JavaScript doesn't keep 999 undefined values. Only
> arr[999] value really exists, undefined will be generated
> automatically then addressing an element.


No, there is a difference between a property that exists and have
the value "undefined" and a property that doesn't exist. Reading
the latter will evaluate to "undefined" as well, but that's because
the language semantics says so (in particular the [[Get]] method
of objects).

There is *no* difference between arr[501] and arr[1500]. They are both
non-existing properties of the array object. The only thing that makes
you think otherwise is that one of them happens to be less than the
length property, and the other greater than.

> But this internal mechanics is really not of interest of the
> end-users. They see what they should see: each array contains
> arrayObject.length elements indexed from arrayObject[0] to
> arrayObject[arrayObject.length-1], there all non-initiated elements
> have undefined value:


> var arr = new Array();
> arr[3] = 1;
> for (i=0; i<arr.length; i++) {
> alert((arr[i]==undefined)? 'undefined' : arr[i]);


Use "===" when comparing to undefined, or you will be surprised
Add arr[6] = null; to see.

Now try
for(i in arr) { // ...
or
alert((i in arr)?...)
and see the difference between initialized and not. Add some
arr[x]=undefined for fun.

Btw, an array literal can also leave places uninitialized:
var arr = [,,,1,,,2,,,];
should have
arr.length == 9 // but IE sucks and says 10.
and only
3 in arr && 6 in arr
be true. The remaining are undefined.

/L
--
Lasse Reichstein Nielsen - http://www.velocityreviews.com/forums/(E-Mail Removed)
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
 
Reply With Quote
 
VK
Guest
Posts: n/a
 
      06-19-2005
> What exactly is an "end-user" of javascript?

Nothing like "amateur" or "beginner", I did not mean *that*. End-user
is a person who's using JavaScript for programming, but who doesn't
program JavaScript engine itself (Using C++/C#). So for him it's
important to know the difference in all contexts between say:
var myVar = 0;
and
myVar = 0
At the same time it's irrelevant to him/her at what phisical address
this var will be allocated and how the system will manage to reallocate
the memory if latter (s)he will do
myVar = "Now it will be a string";
But (s)he must know that it's possible and that it will override the
previous value.

So it's equal for him/her if that "undefined" is just created by
internal sub or indeed was kept somewhere in the memory.

P.S. I'm fixing a VBA (not mine!) with OPTIONBASE changed to 1 for all
arrays. This is the reason of my temp math disability. In my 2nd
attempt please read
arr[999] = 1;
The rest is right then.

 
Reply With Quote
 
Michael Winter
Guest
Posts: n/a
 
      06-19-2005
On 19/06/2005 13:29, VK wrote:

>> What exactly is an "end-user" of javascript?

>
> [...] End-user is a person who's using JavaScript for programming, [...]


Then an end-user, in those terms, should understand how array operations
work, and shouldn't deceive themselves into thinking about array
resizing in memory.

As dynamic resizing is a feature that is often used, I doubt the
performance increase available from using static arrays when finding
values is worth the penalty of reallocation and wasted memory.

[snip]

I think it was agreed during the last round of discussion on
'associative arrays', that the use of such terms is fine if it aids
understanding, but it must not result in disguising what really occurs.
That is, it might help to think of certain aspects of native objects as
exhibiting the behaviour of associative arrays, but the individual must
understand that native objects are /not/ these constructs. The same
should apply to other features of ECMAScript.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
 
Reply With Quote
 
Richard Cornford
Guest
Posts: n/a
 
      06-19-2005
VK wrote:
>> What exactly is an "end-user" of javascript?

>
> Nothing like "amateur" or "beginner", I did not mean *that*.
> End-user is a person who's using JavaScript for programming,
> but who doesn't program JavaScript engine itself
> (Using C++/C#). So for him it's important to know the
> difference in all contexts between say:
> var myVar = 0;
> and
> myVar = 0
> At the same time it's irrelevant to him/her at what
> phisical address this var will be allocated and how
> the system will manage to reallocate the memory if
> latter (s)he will do
> myVar = "Now it will be a string";
> But (s)he must know that it's possible and that it
> will override the previous value.


Not that it is possible that it will overwrite the previous value, but
that it _will_ overwrite the previous value. This is computer
programming; pure mechanical logic with absolutely deterministic
behaviour.

Yes the programmer of javascript does not need to know anything about
the language implementation. They do need to know about the language's
specified behaviour, in as much technical detail as possible. They need
that understanding to use the language well, and they need that
understanding in order to talk about the language to others in common
trems.

> So it's equal for him/her if that "undefined" is just
> created by internal sub or indeed was kept somewhere
> in the memory.


That is exactly the sort of thing that a javascript programmer does need
to comprehend. There is an important difference between a property that
has been created but holds the Undefined value and a property that never
has existed. The distinction is critical to understanding scope chain
Identifier resolution and the prototype chian.

Richard.


 
Reply With Quote
 
VK
Guest
Posts: n/a
 
      06-19-2005
We're talking around Dr John Stockton's definition that joins in one
sentence two totally different context: low-level memory management and
high-level programming entity behavior. (This is why I did not accept
it).

No, the engine doesn't fill non-initialized array members with some
placeholders. That would be a waste of memory. (Low
level)
Yes, *programmically* each array consists of (array.length) members,
where non-initialized members have undefined value. (High level)

So *programmically* my proof is here:

var arrayObject = new Array(10);
arrayObject[100] = 1;
for (i=0; i<arrayObject.length; i++) {
// 100 cicles, 100 values
}

And *programmically* the properties collection
check below doesn't proof anything, because we're
downcasting Array back to Object and studying it
from that level. So we actually do (in Java notation):
(Object)arrayObject

for (objectProperty in arrayObject) {
// 1 cicle, 1 value for (Object)arrayObject
}

JavaScript frees programmer from the "manual" memory allocation, so
*any* array can have as many members as it allowed by the language
specs. So if we want to stay on the same low-level (where array
consists only from defined members), then

var arrayObject = new Array();
really means:
var arrayObject = new Array(1073741822); // for Windows platforms

and

var arrayObject = new Array(10);
really means:
// var arrayObject = new Array(10); // silently ignored
var arrayObject = new Array(1073741822); // for Windows platforms

But do we really want to stay so low? I would propose to move on the
normal programming level, where array has (array.length) members, and
declaration Array(10) indeed means something, and one should use push()
method to nicely add new members to an array.


P.S. So much for hash

 
Reply With Quote
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      06-19-2005
"VK" <(E-Mail Removed)> writes:

> We're talking around Dr John Stockton's definition that joins in one
> sentence two totally different context: low-level memory management and
> high-level programming entity behavior. (This is why I did not accept
> it).


Difinition of what? Please include at least some context of what your
are replying to.

> So *programmically* my proof is here:
>
> var arrayObject = new Array(10);
> arrayObject[100] = 1;
> for (i=0; i<arrayObject.length; i++) {
> // 100 cicles, 100 values
> }



Proof of what. How does this differ from:

var arrayObject = new Array(10); //arrayObject.length == 10
for (i=0; i < 101; i++) {
// ... ?
}

> And *programmically* the properties collection
> check below doesn't proof anything, because we're
> downcasting Array back to Object and studying it
> from that level. So we actually do (in Java notation):
> (Object)arrayObject


While I think I understand your point, comparing Javascript
to a class based language is rarely productive.


> JavaScript frees programmer from the "manual" memory allocation, so
> *any* array can have as many members as it allowed by the language
> specs. So if we want to stay on the same low-level (where array
> consists only from defined members), then
>
> var arrayObject = new Array();
> really means:
> var arrayObject = new Array(1073741822); // for Windows platforms


No. The latter has arrayObject.length == 1073741822, not 0.
(And the length is an unsigned 32 bit number, so the highest index
in is
var ar = new Array();
ar[4294967294] = 1;
alert(ar.length); // 4294967295
)

> var arrayObject = new Array(10);
> really means:
> // var arrayObject = new Array(10); // silently ignored
> var arrayObject = new Array(1073741822); // for Windows platforms


You are trying to use Java arrays to understand and/or explain
Javascript arrays. However, the main difference is that in Java,
arrays have a fixed length, while in Javascript, they are dynamic.


> But do we really want to stay so low? I would propose to move on the
> normal programming level, where array has (array.length) members, and
> declaration Array(10) indeed means something, and one should use push()
> method to nicely add new members to an array.


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

/L
--
Lasse Reichstein Nielsen - (E-Mail Removed)
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
 
Reply With Quote
 
Richard Cornford
Guest
Posts: n/a
 
      06-19-2005
VK wrote:
> We're talking around Dr John Stockton's definition that
> joins in one sentence two totally different context:
> low-level memory management and high-level programming
> entity behavior. (This is why I did not accept it).
>
> No, the engine doesn't fill non-initialized array members
> with some placeholders. That would be a waste of memory.
> (Low level)
> Yes, *programmically* each array consists of (array.length)
> members, where non-initialized members have undefined
> value. (High level)


But Arrays do not have - array.length - members at the high level, they
have a - length - property that describes the upper limit of their
members with 'array index' names. Useful if you want to perform a loop
that will catch all of the members with 'array index' names.

> So *programmically* my proof is here:
>
> var arrayObject = new Array(10);
> arrayObject[100] = 1;
> for (i=0; i<arrayObject.length; i++) {
> // 100 cicles, 100 values


101 cicles, 101 values. Give up the drink.

> }


Proof of what? We know that the loop will catch all of the array members
with 'array index' names, and we know that non-existent property names
will result in the Array's [[Get]] method returning the Undefined value
when used in a property accessor. So we expect 101 values only one of
which is not the Undefined value, because the array only has one member
that has an 'array index' name.

> And *programmically* the properties collection
> check below doesn't proof anything, because we're
> downcasting Array back to Object


Will you stop applying this class-based terminology to javascript. There
is no casting here. The Array is, was, and always will be, an instance
of the native ECMAScript object.

> and studying it from that level.
> So we actually do (in Java notation):
> (Object)arrayObject


You cannot cast objects in javascript because they are
all_of_exactly_the_same_type.

> for (objectProperty in arrayObject) {
> // 1 cicle, 1 value for (Object)arrayObject
> }
>
> JavaScript frees programmer from the "manual" memory
> allocation, so *any* array can have as many members
> as it allowed by the language specs.


The specification does not impose any limits on the number of members a
native ECMAScript object may have. An Array may not nave more 'array
index' named members than can be accommodated by the definition of
'array index', but it can have as many members with non-'array index'
names as the implementation and available memory will put up with.

> So if we want to stay on the same low-level (where array
> consists only from defined members), then
>
> var arrayObject = new Array();
> really means:
> var arrayObject = new Array(1073741822); // for Windows platforms
>
> and
>
> var arrayObject = new Array(10);
> really means:
> // var arrayObject = new Array(10); // silently ignored
> var arrayObject = new Array(1073741822); // for Windows platforms


How is it that you feel it appropriate to conjure this nonsense up from
your immagenation and write it down as if it means something?

> But do we really want to stay so low? I would propose to
> move on the normal programming level, where array has
> (array.length) members, and declaration Array(10) indeed
> means something, and one should use push() method to nicely
> add new members to an array.


The "normal programming level" is to attempt to understand the language
being used, not make up stories about it off the top of your head.

> P.S. So much for hash


"What! drugs? I always thought your articles were a little too
inspired." (from: 'Sir Henry at Ndidi's Krall' by Vivian Stanshall
1984)

Richard.


 
Reply With Quote
 
VK
Guest
Posts: n/a
 
      06-19-2005
OK
JavaScript array is not really an array.
arrayObject.length keeps the highest index you managed to use so far.
It has *no* connection with the actual array's length, it's just called
so for further convenience.
Array contains as many elements as you initialized *yourselve*. If you
vant to know the real array length, you have to treat array as hash
table (map, collection) and iterate through its key/value pairs.
As the latter is the only way to treat JavaScript's array properly, it
doesn't really matter what your're doing: adding key/value pair to the
hash or adding indexed alement to the array. You're dealing with the
same object anyway.
push(), pop(), and other array methods are not needed in JavaScript.

I agree on everything stated above. Just one humble ask: please do not
put *this* to FAQ's.
Eppur si mouve!

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, its engine has some strange behavior:

if you do arrayObject[SomeNumber] = someValue, it counts it in
arrayObject.length
It also lets you to use standard array methods on this member. (1st
category)

if you do arrayObject[SomeString] = someValue, the engine doesn't it in
arrayObject.length
and you cannot use standard array methods on this member. (2nd
category)

Until JavaScript/JScript engine producer will rectify this obvious bug,
you need to be very attentive while putting new members in your
arrayObject.
As soon as array index is not an integer, new members falls into the
2nd category with all above listed consequences.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
hash of hash of hash of hash in c++ rp C++ 1 11-10-2011 04:45 PM
Hash#select returns an array but Hash#reject returns a hash... Srijayanth Sridhar Ruby 19 07-02-2008 12:49 PM
Benchmark segfault [Was: Array#inject to create a hash versus Hash[*array.collect{}.flatten] ] Michal Suchanek Ruby 6 06-13-2007 04:40 AM
Array#inject to create a hash versus Hash[*array.collect{}.flatten] -- Speed, segfault Anthony Martinez Ruby 4 06-11-2007 08:16 AM
Sort by hash vaule, an array of hash references fahdsultan@gmail.com Perl Misc 11 10-10-2005 09:35 PM



Advertisments