/    Sign up×
Community /Pin to ProfileBookmark

Explaination please on associative arrays

The following is an exercise to see if I understand the concepts of an associative array using javascript. I seem to be able to understand what is happening in about 50% of the script.

I am interested in why I get the displays on separate lines when I click on some of the buttons, but not when I click some others. I’m unclear from where the extra fields are comming from.

Please take a look at the code and displays to see if you can explain what is happening with this script.

[code=php]
<html>
<head>
<title>Array Test</title>
<script type=”text/javascript”>
var HArr = new Array(); // create ‘hash’ (associative) array

function putHArr(key,info) { // save ‘info’ at ‘key’ array position
if (HArr[key] == undefined) { HArr.push(key); } // if not already defined, create element position
HArr[key] = info; // save ‘info at ‘key array position
}
function getHArr(key) { // get ‘info’ at ‘key position
return HArr[key];
}

function SetupHArr() {
Data = new Array();
Data[0] = ‘Boop, Betty,King World’;
Data[1] = ‘Mouse,Mickey,Disney’;
Data[2] = ‘Bunny,Bugs,Warner Bros.’;
Data[3] = ‘Fudd,Elmer,Warner Bros.’;
Data[4] = ‘Duck,Donald,Disney’;
Data[5] = ‘Dog,Goofy,Disney’;
Data[6] = ‘Cat,Tom,MGM’;
Data[7] = ‘Mouse,Jerry,MGM’;
var str = ”;
for (i=0; i<Data.length; i++) {
var info = Data[i].split(‘,’);
var key = info.shift();
putHArr(key,info.join(‘|’)); str += i+’=’+key+’|’+info.join(‘|’)+'<br />’;
}
Display(‘Setup created:<br />’+str);
}

function showHArr1() {
var str = ‘HArr contents<br />’;
for (var i=0; i<HArr.length; i++) { str += i+’=’+HArr[i]+’|’+getHArr(HArr[i])+'<br />’; }
Display(str); // display is as expected
// Displays with one record per line
// creates: 0=Boop:Betty,King World
// : 1=Mouse:Jerry,MGM // note: Mouse,Mickey replaced by Mouse,Jerry [expected]
// … : 6=Cat:Tom,MGM // and hash array is less than Setup array (Data below)
}

// previous 2 functions work as expected but
// next 2 functions don’t display results as expected ???

function showHArrKeys() { // display current ‘keys’ in HArr
var str = ‘HArr keys<br />’;
for (var key in HArr) { str += key+'<br />’; } // create string of ‘keys’ from HArr
Display(str);
// creates: 0 Boop 1 Mouse 2 Bunny … 6 Cat
// don’t know where numbers (0..6) are comming from ???
// and don’t know where RETURNs come from after 0..6 display ???
}

function showHArr2() {
var str = ‘HArr contents<br />’;
var i = 0;
for (var key in HArr) { str += i+’=’+key+’:’+getHArr(key)+'<br />’; i++; }
Display(str);
// display is NOT as expected
// causes RETURNs after key AND record ???
// and displays elements of 0..13 ???
}

// following 2 function work correctly as expected
function ShowRec() {
var key=document.getElementById(‘HArrKey’).value;
Display(key +’|’+ getHArr(key));

}
function Display(str) {
document.getElementById(‘contents’).innerHTML = str;
}
</script>
</head>
<body>

<table border=’0′>
<tr><td>
<button onClick=”SetupHArr()”>Setup Hash array (OK!)</button>
</td><td>
<button onClick=”showHArrKeys()”>Show Keys of Hash(???)</button>
</td></tr>

<tr><td>
<button onClick=”showHArr1()”>Show Hash array (OK!)</button>
</td><td>
<button onClick=”showHArr2()”>Alt. Hash display (???)</button>
</td></tr>
</table>

<br />
Key <input type=”text” id=’HArrKey’ value=”” />
<button onClick=”ShowRec()”>Get</button>
<p /><div id=”contents”></div>
</body>
</html>
[/code]

I would like to understand the difference between the button displays. ?
The top left buttons appear to display as expected but
the top right buttons display extra fields or line breaks.

Thank you for any thoughts.

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@MigAug 22.2007 — To be honest, it seems as though many of the confusing readouts you are getting from traversing this array are simply because your approach is overly complex.

In order to simplify for yourself what is happening, it would probably be a better idea to merge some of the many functions - i.e. get rid of the unnecessary ones, such as getHArr(), Display(), etc. - and generally just break it down into a basic, raw form. If the code is in fewer places, it will be a lot easier to see and control what is happening.

It also looks as though it would be easier for you to use a multi-dimensional array, as opposed to splitting strings.

These are just some suggestions, as it's hard for me to see what you are trying to do. It just looks as though you are tying yourself in knots and making it harder for yourself to understand.
Copy linkTweet thisAlerts:
@LeeUAug 22.2007 — See if this doesn't help out a bit.
Copy linkTweet thisAlerts:
@JMRKERauthorAug 22.2007 — @Mig,

Sorry for the confusion but thanks for the comments.

What I am trying to do is understand the index relationship of associative arrays in JS.

The guts of the script are the first two functions:

putHArr(key,info) pushes the 'info' to the last element of the HArr array with 'key' begin the element location. If the element is already defined, then the 'info' over writes the previously stored value.

getHArr(key) retrieves the information stored at the 'key' element


SetupHArr() is just an initialization function. The function uses the putHArr() to create some data to test with. The data could be from CSV file or other character delimited text file of the users choosing. It demonstrates that 8 records [0..7] are read but only 7 new records are created in HArr as the 'Mouse' key over writes the first entry. All here works as expected.

The <BODY> of the script only uses BUTTONS to manipulate the information in HArr and use the Display() function to write to the innerHTML of a screen section. The only function of this is to see how the HArr can be manipulated and displayed. The ShowRec() function uses the text box to display a particular element of the HArr using a 'key' entered by the user. All here works as expected.

The showHArr1() function works as expected as well. It accesses each record of the HArr array and displays both the 'key' and 'value' on a separate line of the display. The '0=' ,'1=', ... '6=' is expected because of the way the display is created.

Now comes the two functions that I'm having trouble understanding what the displays are showing.

I expected ShowHArrKeys() to list 7 keys, each on a separate display line.

What I get is a number (0 to 6) and the expected 'key' displayed, but EACH on a separate line. I don't expect the number to be displayed at all as I did not put it into the display 'str' created for the screen output. Where does this come from? I expected 7 lines of output (0..6) but instead get double that. Why?

I expected the showHArr2() function to create a similar display (7 lines) to the showHArr1() function, but I'm getting something completely different. For the showHArr2() function I'm getting 14 lines of output with elements numbered 0 to13. I assume it is for a similar reason as for the ShowHArrKeys() function, but I don't know this for sure.

So the bottom line is that I want to understand what is going on here. While the code above contains 'goofy' data records, I would like to use the concepts in other scripts that I have yet to create. I don't like to use code that I don't fully understand. The actions of most of the script above I understand, it just the last two function displays that I can't figure out. Yes, I could use single or multiple dimension arrays, but I think I understand how they work (or at least I can understand all I do with them when used). I'm breaking new ground in my learning cycle and this is something I thought the forum members might help me out with.

Thanks again for your (or anyone's) considerations and thoughts. ?
Copy linkTweet thisAlerts:
@JMRKERauthorAug 23.2007 — Thanks LeeU.


That did help a little ?

and also showed me some others have thought about this before me.

I am still confused in my program above as to where the extra lines and record numbers come from when I try to display the keys and records with the functions ShowHArrKeys() and showHArr2()

The program almost works as I expect, but I just don't understand where the extra output is coming from. ?


I can use the working ShowRec() and showHArr1() functions and ignore/never use the other functions that incorrectly (to my thinking) should display the same information.

Again thanks for the reference.
Copy linkTweet thisAlerts:
@vwphillipsAug 24.2007 — consider

[CODE]
function showHArrKeys() { // display current 'keys' in HArr
var str = 'HArr keys<br />';
// for (var key in HArr) { str += key+'<br />'; } // create string of 'keys' from HArr
for (i=0;i<HArr.length;i++) { str += HArr[i]+'<br />'; } // create string of 'keys' from HArr
Display(str);
// creates: 0 Boop 1 Mouse 2 Bunny ... 6 Cat
// don't know where numbers (0..6) are comming from ???
// and don't know where RETURNs come from after 0..6 display ???
}
[/CODE]


I conclude that the 'key' includes the index and key name.
Copy linkTweet thisAlerts:
@Mr_MooAug 24.2007 — Just to throw my 2 cents in here: [url=http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/]Associative Arrays are BAD[/url]. One should use an object to create a Hash.
Copy linkTweet thisAlerts:
@JMRKERauthorAug 24.2007 — Thanks everyone for the comments and links.

The link by 'Mr Moo' was somewhat informative to me.

At least if I use this code in a program, I will be especially careful and attempt to double-check all functions. I like the power of 'associative arrays', but I see now that their set-up and usage are different on other languages (PERL and C+, for example) and I cannot always carry over my concepts to what I expect to happen to that which actually happens!

I think a lot of my confusion arises from not having a clear understanding about the difference of an 'object' and 'array' and that 'arrays' are 'objects'. Given another lifetime I might be able to use the language, but by then there will probably be a replacement language for JS called 'Babel' and I'll only need to stick a fish in my ear to understand it. ?

Thanks for the help. In this case the forum. for me at least, fulfilled its function of information distribution.
Copy linkTweet thisAlerts:
@KorAug 24.2007 — have a look on the difference between associative arrays (objects) and ordered arrays when using JSON
Copy linkTweet thisAlerts:
@DokAug 25.2007 — My 2 cents as well
Just to throw my 2 cents in here: Associative Arrays are BAD. One should use an object to create a Hash.[/QUOTE]I read the article and the comments.

From what I understand people are complaning about API's extending the prototype object of built-in objects and particularly the Array object.

This is mainly from the point of view that everyone expects the for..in operation to only enumerate key/values in the Array object which they have instantiated - not the prototype properties that would result from extending the Array.prototype object.

To me this is a very weak argument. As I see it it a lot of people wrongly rely on the [I]assumption[/I] of how the for..in operation [I]should[/I] work - not on how it actually [I]does[/I] works. So this is not an assumption about JavaScript but about the users working with JavaScript. The title of the article could rightly be "JavaScript Users use of “Associative Arrays” Considered Harmful".

One can then argue that I should write my code as the majority if I expect the majority to use whatever API I might have constructed. This is true but is does not make associative arrays harmful. This is not just a minor rethoric distinction. It is in effect a restriction on how any programmer can use the JavaScript language. The language has prototype based inheritance yet many of the projects I see try too circumvent this by adding either class-like based inheritance schemes, adding private properties and methods with closures and restrictive constructs like the one in question.

I think you should turn the argumentation around and look at the obvious faulty misuse of the for..in loop instead. Not that the for..in loop is broken but the fact that you rely on it to work in a specific manner when enumerating arrays. The problem is not arrays - the problem is relying on everyone else to impose the same restriction that you do. The problem is not the language - the problem is the users use of the language.

I have seen this discussion elsewhere most of the time related to extending the Object.prototype and the arguments most of the time similar to the one in this article. "Don't extend the Object.prototype - we are not expecting you to do this" and this is just like saying "don't use one of the most powerful features of JavaScript as we like to use the for..in loop the way we are used to". Well the "way you are used to" is a major design error in any software. Since one can easily detect whether a property is in the instantiated object or in the prototype object I think the restriction is ridiculous.

Why limit the functionality of a language just because you are used to doing it a certain way?
×

Success!

Help @JMRKER spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...