Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Array and Hash (Associative array) in JavaScript v.3.0

Reply
Thread Tools

Array and Hash (Associative array) in JavaScript v.3.0

 
 
Kevin Newman
Guest
Posts: n/a
 
      07-28-2005
I'm confused as to why that should break it (commented):

Test = new function() {

// defines as an array with .length = 0
var $listeners = new Array();

function _NotifyListeners($newHash) {
// loops through array using inherited object looping
// Does accessing in this way redefine it as an object?
for (var $key in $listeners)
$listeners[$key].Update($newHash);
};

this.AddListener = function($obj) {
if (!$obj.Update) return false;

// adds an object to the array (integer based index)
// really just emulating push(), so that it works on IE 5.0
$listeners[$listeners.length] = $obj; // still array

return true;
};
this.RemoveListener = function($obj) {
// loops through array using inherited object looping
// Does accessing in this way redefine it as an object?
for (var $key in $listeners)
if ($listeners[$key] == $obj)
delete $listeners[$key];
};

...

};


As far as I understand, it is never redefined as Object, and remains an
Array. I just use its inherited functionality from the object (since in
javascript all types inherit from Object) to iterate over it, and to
delete properties (or array elements).

I have admittedly not tested the RemoveListener method - however the
MSDN JScript reference (yeah, I know, it can't be considered the final
voice) says that using delete to remove array elements is perfectly fine
(and I have tested that on other platforms, even Netscape 4.x).

After writing all this, I guess this whole thread is off topic, since
I'm not actually using the array as a hash (I'm using integer indices).
So I apologize if this is off topic.
 
Reply With Quote
 
 
 
 
Kevin Newman
Guest
Posts: n/a
 
      07-28-2005
VK wrote:
> Full code of the constructor?


Oh, do you want to see where I'm using this? I'm using it here:

http://www.unfocus.com/Projects/Hist...storyKeeper.js
 
Reply With Quote
 
 
 
 
Michael Winter
Guest
Posts: n/a
 
      07-28-2005
On 28/07/2005 19:52, Kevin Newman wrote:

> I'm confused as to why that [using the length property to simulate
> the push method] should break it (commented):


VK is mistaken.

[snip]

> var $listeners = new Array();


I'm curious: why are all of your identifiers prefixed by dollar symbols?
That particular character is meant for use with mechanically created
code (though that isn't enforced, of course).

[snip]

> I have admittedly not tested the RemoveListener method - however the
> MSDN JScript reference [...] says that using delete to remove array
> elements is perfectly fine [...].


You should have no trouble using the delete operator with native
objects. However, using it with a host object in IE (such as a DOM
object) will cause an error, even if you created the property in question.

> After writing all this, I guess this whole thread is off topic, since
> I'm not actually using the array as a hash (I'm using integer indices).


You're not using it as a hash, as such, but you're not using it as an
array either. You're taking advantage of the fact that it increments a
value, rather than you doing it yourself.

I would (and in fact, do) use a list for similar code. Though a
comparison between the properties of sequential and linked data
structures don't really apply here (as Array objects aren't likely to be
backed by an array), there are some parallel from a design perspective.
You also need to consider duplicate element checks during insertion;
for..in statements aren't that efficient outside IE.

Finally, and I'm just being picky here, using an array in this manner is
also self-limiting (though that limit is extremely large) as, in time,
you'd run out of numbers.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
 
Reply With Quote
 
Kevin Newman
Guest
Posts: n/a
 
      07-28-2005
Michael Winter wrote:
> I'm curious: why are all of your identifiers prefixed by dollar symbols?


I used those because I intend to compress my project with Dean Edwards'
Packer script for distribution.

http://dean.edwards.name/packer/


> I would (and in fact, do) use a list for similar code.


Do you have an example of what you mean by a list? I found a script that
implements CList (on mozilla.com or something), but it has a lot of code
in it, and felt like overkill for what I want to use it for.


> Finally, and I'm just being picky here, using an array in this manner is
> also self-limiting (though that limit is extremely large) as, in time,
> you'd run out of numbers.


That's pretty picky the number 15 is probably way more than should
ever be used with the script I'm using this for.
 
Reply With Quote
 
Richard Cornford
Guest
Posts: n/a
 
      07-28-2005
Kevin Newman wrote:
> Interesting Article.


Just don't make the mistake of failing to appreciate that, like anything
written by VK, you will know less as a result of reading it that you
would have if you hadn't bothered.

> I have been criticized for using the array type
> as a hash (sort of) in a script that I created:
>
> Test = new function() {
>
> var $listeners = new Array();
>
> function _NotifyListeners($newHash) {
> for (var $key in $listeners)
> $listeners[$key].Update($newHash);
> };
>
> this.AddListener = function($obj) {
> if (!$obj.Update) return false;
> $listeners[$listeners.length] = $obj;


In assigning a reference to an object to a member of the array using the
array's length you are using the array as an array, because you are only
assigning members that have 'array index' property names. That doesn't
appear to be necessary in this case and the real role of the array here
is that its length is effectively a self incrementing value (each new
addition of an 'array index' property of $listeners.length makes the
array one item longer), and so provides a sequence of unique property
names.

If you kept your own numeric 'length' property, and explicitly
incremented it upon assignment you could use an Object to achieve the
same effect. The only practical difference would be that the Object's
[[Put]] method is simpler (and so probably quicker) than the special
[[Put]] method used by Arrays, and you would have less need to worry
about using - for/in - and having unexpected properties enumerated (as
Objects are less likely targets for prototype extensions than Arrays).

> if ($obj.Load)
> $obj.Load($currentHash);
> return true;
> };
> this.RemoveListener = function($obj) {
> for (var $key in $listeners)
> if ($listeners[$key] == $obj)
> delete $listeners[$key];


The - delete - operator does not have any impact on the length property
of an Array, so even deleting the last 'array index' property in an
array will not decrement the length. It is a good thing that javascript
arrays are sparse as this strategy would otherwise involve an ever
expanding memory use.

> };
>
> ...
>
> };
>
> I did this because it is convenient to use for ( in ) loops,


Which work the same for all objects (in the sense of using the same
specified algorithm, host objects do not have well defined rules as to
which properties will be enumerable).

> and because it is also convenient to use the length
> property to create a new key to hold the added listener.


I don't see much in it, the alternative would just be:-

Test = new function() {
var $listeners = {};
var key = 0;
...
this.AddListener = function($obj) {
if (!$obj.Update) return false;
$listeners[++key] = $obj;
if ($obj.Load)
$obj.Load($currentHash);
return true;
};
...
};

- and work the same.

> I wonder what you think about doing something like that.
> Is it abuse to use an Array in this way?


To avoid incrementing your own counter? It seems over the top to take on
the baggage of an array just for that feature.

Incidentally, the dollar symbol is specifically mentioned in ECMA 262
(3rd edition, section 7.6) as being intended for use only in machine
generated code, so it should probably be avoided in javascript (that is
not machine generated). And because prefixing identifiers with dollar
symbols has special meaning in some other languages their use in
javascript (where they have no special meaning beyond signifying machine
generated Identifiers) is likely to be misleading.

Richard.


 
Reply With Quote
 
RobG
Guest
Posts: n/a
 
      07-28-2005
VK wrote:
>>I think you need to reconsider your comments about array length (my
>>wrapping of comments):
>>
>> "var arrayObject = new Array(3); // arrayObject has 3 undefined
>> // elements"
>>
>>That misconception has been repeated many times throughout your article.

>
>
> The misconception (or a plain stubborness) I'm trying to fight with has
> been indeed discussed many times and its wrongness is demonstrated very
> clearly in the article.


If you are discussing your stubbornness, then yes, it is demonstrated.

> I encourage you to go through again of:
> <http://www.geocities.com/schools_ring/ArrayAndHash.html#Array_Length>
> and below, as well as apply other array methods of you choice.


Subsequent readings have not changed the text or my understanding of it.

> This misconception (let's stick to this softer term) erises from the
> brute mix of the low level memory allocation and the high level
> programming entity behavior.


Then it is all the more strange that you did not indicate how to get rid
of unwanted values in an array (though I note that you seem to be
working on an 'array methods' page), nor that it is likely that the
difference in the amount of memory consumed by the following arrays:

var x = new Array( 1 );
var y = new Array( 10000 );

is either zero or trivial.

> As I may notice from your previous postings, the matrix transpoding is
> your hobby(?). So especially for you it is vital to understand what are
> you really working with and how will it respond to the applied methods.


I'm not aware of 'matrix transponding', but I'll look it up.

My interest is mostly in attempting to gain a better understand
mathematics. Implementing operations in a programming language requires
that you either learn or develop algorithms for performing those
operations - it's the next best thing to teaching.

JavaScript is a very convenient language as I can work on nearly any
platform that has a browser and text editor with almost no compatibility
issues.

>>The ECMA specification does not say that the length property is the
>>number of elements in the array, it is defined as being numerically
>>greater than the name of every property whose name is an array index
>>(which means it will be equal to the largest index plus 1 or greater).
>>
>>For all practical purposes, it is irrelevant whether:
>>
>> var x = new Array( 99 );
>>
>>actually creates an array of 99 elements or not, but it does
>>explicitly create an array with a length property of 99. And that is
>>all you can say with certainty.

>
> <http://www.geocities.com/schools_ring/ArrayAndHash.html#Array_Length>
> and further. Read the code samples in the grayed area. *Read it* , not
> just pass over as "a method implementation error".


Constantly referencing your own work to support your argument is
pointless. If you have something new to present, let's see it - or
point out exactly why you think I'm in error.

Your statement at that link is:

"Each array has length property indicating the total amount of
elements (registered "data holders") currently containing in
the array."

Which is just one of many similar statements in the page that reiterates
your view. Constant repetition is not logical argument (that sounds so
Python-esque ).

>>An important property not mentioned by your page is that any element
>>with an index not less than the length will be deleted, so if you have
>>an array with length 10 and you set it to 1, any element with index of
>>1 or greater is deleted.

>
> Yes, as well is if you assign arrayObject = [] then all elements will
> be removed. I did not want to mention in a public reading that the
> Array.length can be used as a brute force ReDim (alloc) method. What


Above you showed concern for memory management, but now it doesn't matter?

> you don't know will not hurt you


Ignorance is bliss?

> Array has enough methods to
> accomplish it more gracefully and reliably.


But you didn't mention any of them (broken 'array methods' link noted).
Are you suggesting that changing the length of an array is an
unreliable way of removing elements?

That notion may have come from the blending of JavaScript arrays with
DOM concepts/methods. The two are not clearly separated in your
article, I think they should be.

Your page is quite good, most of what it says is useful and at a level
most newcomers will understand. But readers should not be taught things
that are inconsistent with fundamental principles.



--
Rob
 
Reply With Quote
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      07-29-2005
"VK" <> writes:

>> $listeners[$listeners.length] = $obj;

>
> This is actually where I stoke because this code should not work at
> all. Unless somewhere below you do $listeners.length++ and *then* it's
> an abuse. Otherwise $listeners.length is always 0.


No. The length property of an Array is always larger than the largest
used array index, so when you assign to index 0, the length becomes
1, etc.

/L
--
Lasse Reichstein Nielsen -
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
 
Reply With Quote
 
Kevin Newman
Guest
Posts: n/a
 
      07-29-2005
Richard Cornford wrote:
> The - delete - operator does not have any impact on the length property
> of an Array, so even deleting the last 'array index' property in an
> array will not decrement the length. It is a good thing that javascript
> arrays are sparse as this strategy would otherwise involve an ever
> expanding memory use.


I was counting on the fact that they are sparse arrays - it takes the
element out of the for ( in ) loop, which is why it is so convenient (it
doesn't take it out of for(; loops though obviously).


> To avoid incrementing your own counter? It seems over the top to take on
> the baggage of an array just for that feature.


This makes sense. I always try to write easy to maintain (and read)
code, and still have efficiency and performance (I'm still learning,
though, so I don't always succeed). Since what you've said makes more
sense from a design view, and should have better performance, I'll take
your advise


> Incidentally, the dollar symbol is specifically mentioned in ECMA 262
> (3rd edition, section 7.6) as being intended for use only in machine
> generated code, so it should probably be avoided in javascript (that is
> not machine generated). And because prefixing identifiers with dollar
> symbols has special meaning in some other languages their use in
> javascript (where they have no special meaning beyond signifying machine
> generated Identifiers) is likely to be misleading.


Hmmm... I actually only use that because I intend to compress this code
for distribution using Dean Edwards' packer script:

http://dean.edwards.name/packer/

I've also noticed that some of the older browsers (3.0 era) don't like
that character in the identifiers, so I may just take them out, or
replace them with "_" it's easier that way anyway, because I don't have
to remember the check if any other identifier starts with the same first
letter (ex: Dean's tool replaces $variable with v).

I use them in php all the time as well, so it is quite natural to put
them there

Thanks for the great info!

Kevin N.
 
Reply With Quote
 
VK
Guest
Posts: n/a
 
      07-29-2005

RobG wrote:
> If you are discussing your stubbornness, then yes, it is demonstrated.


Oh yeh! But not from my part. This why I called it once "a discussion
about who's God is better".

You may read an interesting discussion with Mr. Nielsen about the
previous variant of the article:
<http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/c12423afa53a28f8/bcf7ad952e27c998#bcf7ad952e27c998>

> Subsequent readings have not changed the text or my understanding of it.


I see... So I guess you went through the example with the slice()
method and it did not change your clear understanding that this method
(as nearly all others) is simply broken...
It gives a good credit to your believe. My good luck to you to use
arrays in the matrix analysis. It's going to be as difficult as
navigate across the globe while thinking that the Earth is flat and
stays on three elephants.


>The ECMA specification does not say...


ECMA doesn't need to say anything particular about array, as well as
define what "object", "algorithm", "program" and so is. These entities
appeared long before ECMA. So if you need to know what array is, ECMA
is not an authority of any kind. Their humble task was just include
properly and in proper relations with other sections, something that
was invented and described long before anyone of them got her/his first
payroll check. In this concern IBM repository is much more reliable
source of information:
<http://publib.boulder.ibm.com>


P.S. And yes, sorry for the broken link on array method. I had to drop
to take an urgent order. So far I just removed it.

 
Reply With Quote
 
RobG
Guest
Posts: n/a
 
      07-30-2005
VK wrote:
> RobG wrote:
>
>>If you are discussing your stubbornness, then yes, it is demonstrated.

>
>
> Oh yeh! But not from my part. This why I called it once "a discussion
> about who's God is better".
>
> You may read an interesting discussion with Mr. Nielsen about the
> previous variant of the article:
> <http://groups-beta.google.com/group/comp.lang.javascript/browse_frm/thread/c12423afa53a28f8/bcf7ad952e27c998#bcf7ad952e27c998>
>
>>Subsequent readings have not changed the text or my understanding of it.

>
>
> I see... So I guess you went through the example with the slice()
> method and it did not change your clear understanding that this method
> (as nearly all others) is simply broken...


Yes I did - I clearly understand what it does.

I can accept you expressing your opinion within this forum, but if you
are going to try to teach people about JavaScript arrays you need to
clearly separate fact from opinion.

Using your example and with a copy of the ECMAScript Language
Specification 3rd Edition December 1999 handy:

Quote:
var arrayOne = new Array();
arrayOne[0] = "foo"
arrayOne[100] = "bar"
var arrayTwo = arrayOne.slice(0,50);
// arrayTwo.length == 50
arrayTwo will consist of the elements 0 up to but not including 50 of
arrayOne and therefore have a length of 50 (as per section 15.4.4.10).
arrayTwo[0] will be "foo"; all the other elements are undefined.

arrayTwo may actually have one defined element and 49 undefined ones,
or just one defined element and a length of 50 - however it is
actually implemented is irrelevant 99.99% of the time.

Quote:
// But:
var arrayTwo = arrayOne.slice(99,200);
// arrayTwo.length == 2
// Only "in-within array" elements are counted
Which is exactly as per the specification - if the 'end' (in this case
200) is beyond arrayOne's length, then only the elements up to the end
of arrayOne are included. The second slice operation is the same as:

arrayTwo = arrayOne.slice( 99, arrayOne.length );

or

arrayTwo = [ arrayOne[99], arrayOne[100] ];

or

arrayTwo[1] = arrayOne[100];

in all cases, arrayTwo[0] will be undefined and arrayTwo.length = 2.

You then go on to assert:

Quote:
As you can see, despite that mechanically (on the memory level) we
have only two elements in the entire arrayOne (arrayOne[0] and
arrayOne[100]), programmatically we have one continuos array of 101
element in total:
"foo", undefined, undefined, ... , undefined, "bar"
Which is your interpretation of things. Rather than use the
specification to state exactly what has occurred, you have chosen to
introduce your own jargon and leave readers confused.

You need to decide if you are teaching ECMAScript Language or VK's
opinion on life, the universe and everything.

> It gives a good credit to your believe. My good luck to you to use
> arrays in the matrix analysis. It's going to be as difficult as
> navigate across the globe while thinking that the Earth is flat and
> stays on three elephants.


Is it reasonable to make inferences about my system of beliefs based
on usage of a particular programming language? ;-p

And if my success so far is any measure, I'd have found your challenge
a doddle - pity the darn thing is an ovate spheroid (or so some believe).

>
>>The ECMA specification does not say...

>
>
> ECMA doesn't need to say anything particular about array, as well as
> define what "object", "algorithm", "program" and so is. These entities
> appeared long before ECMA. So if you need to know what array is, ECMA
> is not an authority of any kind. Their humble task was just include
> properly and in proper relations with other sections, something that
> was invented and described long before anyone of them got her/his first
> payroll check. In this concern IBM repository is much more reliable
> source of information:
> <http://publib.boulder.ibm.com>


And that's the central issue - clearly pointing out on the one hand
what the spec says and on the other how arrays or other objects are
used in general in other contexts.

The ECMAScript Language specification is not an authority on arrays in
general, but it does prescribe the basic properties of JavaScript
arrays and therefore must be used as the primary reference when
describing their properties or behaviour.

[...]

--
Rob
 
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
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57