473,707 Members | 2,273 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with for/in loop over associative array

Hi all,

I encountered a problem with looping through an associative array. All
worked perfectly with the following code:

for (var menuItem in this.menuItems) {
doSomething();
}

where this.menuItems is an associative array. The problem occurred when
I added the following function to the Array prototype:

Array.prototype .print_r = function() {
print_the_array _code();
}

After adding this method, the for/in loop took print_r as an element as
well. So besides the items I actually wanted to get from my array, I
also go print_r, which obviously I don't want. Does anyone have a
suggestion what to do with this..?

Thanks in advance,
Yereth Jansen
Jul 23 '05 #1
14 6700
> I encountered a problem with looping through an associative array. All
worked perfectly with the following code:

for (var menuItem in this.menuItems) {
doSomething();
}

where this.menuItems is an associative array. The problem occurred when
I added the following function to the Array prototype:

Array.prototype .print_r = function() {
print_the_array _code();
}

After adding this method, the for/in loop took print_r as an element as
well. So besides the items I actually wanted to get from my array, I
also go print_r, which obviously I don't want. Does anyone have a
suggestion what to do with this..?


Your for should be

for (var i; i < this.menuItems. length; i += 1) {

http://www.crockford.com/javascript/survey.html
Jul 23 '05 #2
Douglas Crockford wrote:
Your for should be

for (var i; i < this.menuItems. length; i += 1) {

http://www.crockford.com/javascript/survey.html


That won't work. I am using an associative array as in a hash. An
associative array does not have a numerical index nor does it have the
property .length set like I want it. ".length" is 0 in all cases.
Jul 23 '05 #3
>> Your for should be

for (var i; i < this.menuItems. length; i += 1) {

http://www.crockford.com/javascript/survey.html


That won't work. I am using an associative array as in a hash. An
associative array does not have a numerical index nor does it have the
property .length set like I want it. ".length" is 0 in all cases.


Do not use Array when you do not need .length. You should be using an
Object. It is best to not use the term "associativ e array" when working
in JavaScript because it will confuse you.

Use the typeof operator on the values you extract, and skip the ones
that are 'function'.

http://www.crockford.com/javascript/survey.html
Jul 23 '05 #4
Douglas Crockford wrote:
Do not use Array when you do not need .length. You should be using an
Object. It is best to not use the term "associativ e array" when working
in JavaScript because it will confuse you.

Use the typeof operator on the values you extract, and skip the ones
that are 'function'.

http://www.crockford.com/javascript/survey.html


Thank you. I was hoping for another answer than this one, but I
suspected it was the only 'solution'. No such luck I guess. Thanks for
helping.

Cheers.
Jul 23 '05 #5
On 18/04/2005 14:24, Yereth Jansen wrote:

[To avoid enumerating user-defined functions]
Douglas Crockford wrote:
[snip]
Use the typeof operator on the values you extract, and skip the ones
that are 'function'.


[snip]
Thank you. I was hoping for another answer than this one, but I
suspected it was the only 'solution'. No such luck I guess.


Well, you could use your own hashtable implementation. You'd sacrifice
the ability to use square bracket notation, but you would have
consistent, controlled behaviour. The archives of this newsgroup (via
Google Groups) will have several implementations (including mine :).

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6
In article <d4**********@a zure.qinip.net> , Yereth Jansen
<ya*********@sp am.cs.uu.nl> writes
Douglas Crockford wrote:
Do not use Array when you do not need .length. You should be using an
Object. It is best to not use the term "associativ e array" when
working in JavaScript because it will confuse you.
Use the typeof operator on the values you extract, and skip the ones
that are 'function'.
http://www.crockford.com/javascript/survey.html


Thank you. I was hoping for another answer than this one, but I
suspected it was the only 'solution'. No such luck I guess. Thanks for
helping.


It's worth saying again : if you say "associativ e array" you are likely
to forget that they are objects with properties, and that a method is
just a property whose value happens to be a function object.

Also, it might not occur to you to build a prototype object to keep all
the methods out of the way.

John
--
John Harris
Jul 23 '05 #7
Yereth Jansen wrote:
All worked perfectly with the following code:

for (var menuItem in this.menuItems) {
doSomething();
}

where this.menuItems is an associative array. The problem occurred when
I added the following function to the Array prototype:

Array.prototype .print_r = function() {
print_the_array _code();
}


It's not exactly clear what you want (ie. on what basis you wish the
print_r to be filtered), but perhaps this quickly-thrown-together
function comes close to what you are looking for:

function showNonPrototyp es(obj) {
var oForbidden = {}; // list of keys on the prototype chain
var prType = ""; // the prototype type
var idx;
if (typeof(obj)==" object") {
var objType = ""+obj; // looking for [object prType]
if ((obj.length + "")!="undefined ") prType = "Array";
else if (objType.substr ing(0,7)=="obje ct ")
prType = objType.substri ng(7);
if (prType && window[prType] && window[prType].prototype)
for (idx in window[prType].prototype) oForbidden[idx] = 1;
for (idx in obj)
if (!oForbidden[idx])
alert(idx); // doSomething();
}
}

// Example
Object.prototyp e.print_r = function () { return "nice array code"; };
var aTest = []; // starts life as an array
aTest.x = "y";
aTest[2] = 45;
aTest.z = "borf";
showNonPrototyp es(aTest);
Csaba Gabor from Vienna
Jul 23 '05 #8
rh
Csaba Gabor wrote:
Yereth Jansen wrote:
All worked perfectly with the following code:

for (var menuItem in this.menuItems) {
doSomething();
}

where this.menuItems is an associative array. The problem occurred when I added the following function to the Array prototype:

Array.prototype .print_r = function() {
print_the_array _code();
}
It's not exactly clear what you want (ie. on what basis you wish the
print_r to be filtered), but perhaps this quickly-thrown-together
function comes close to what you are looking for:

function showNonPrototyp es(obj) {
var oForbidden = {}; // list of keys on the prototype chain
var prType = ""; // the prototype type
var idx;
if (typeof(obj)==" object") {
var objType = ""+obj; // looking for [object prType]
if ((obj.length + "")!="undefined ") prType = "Array";
else if (objType.substr ing(0,7)=="obje ct ")
prType = objType.substri ng(7);
if (prType && window[prType] && window[prType].prototype)
for (idx in window[prType].prototype) oForbidden[idx] =

1; for (idx in obj)
if (!oForbidden[idx])
alert(idx); // doSomething();
}
}

// Example
Object.prototyp e.print_r = function () { return "nice array code"; };
var aTest = []; // starts life as an array
aTest.x = "y";
aTest[2] = 45;
aTest.z = "borf";
showNonPrototyp es(aTest);


That seems rather obtuse -- it could be much better accomplished by
making use of the "hasOwnProperty " function:

for (var k in aTest) {
if(aTest.hasOwn Property(k)) {
alert("Has own property "+k + " : "+aTest[k]);
}
}

If there's a concern for older browsers that don't provide this
function, a reasonably good equivalent can be added as:

if (! Object.prototyp e.hasOwnPropert y) {
Object.prototyp e.hasOwnPropert y = function(pty) {
return (typeof this[pty] != "undefined" &&
(this.construct or
&& this.constructo r.prototype
&& this.constructo r.prototype[pty] !== this[pty]))
}
}

.../rh

Jul 23 '05 #9
Michael Winter wrote:
Well, you could use your own hashtable implementation. You'd sacrifice
the ability to use square bracket notation, but you would have
consistent, controlled behaviour. The archives of this newsgroup (via
Google Groups) will have several implementations (including mine :).

Mike

It crossed my mind and I've seen the sample implementations . Not sure if
it was yours, but if I'll use it I'll make sure to credit your work. ;)
Right now I've decided to not define prototype functions for array, but
rather functions that take an array as an argument, like php does it. I
was just a bit too much into OO programming (yes, even with javascript),
so I was quite stubborn in wanting it to be 'native' functions of the
object.

Anyhue, I will go for the external functions for now, until it doesn't
suite me any longer.

Thanks for the help!

Yereth
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
11197
by: Abdullah Kauchali | last post by:
Hi folks, Can one rely on the order of keys inserted into an associative Javascript array? For example: var o = new Object(); o = "Adam"; o = "Eve";
2
1550
by: Zenobia | last post by:
I have a problem. I need to look up several values stored in arrays. Each value is stored as a pair. The first (number) represents the probability of this item occurring. For instance, in the example below there are 11 items. conFinal = {2:'m',4:'n',6:'ng',8:'r',10:'l',12:'kh',14:'k',16:'s',18:'hl',19:'tl',20:'sh'} Letter 'n' (2nd item) has a probability of 2 chances in 20 (1 in 10] but 'tl' has only a 1 in 20 chance. The chance is
6
2017
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference between London and the previous element is 25 (40-15), London has a 25% chance of being selected. When I call the function getAssocItem to do this I need to send in 2 arguments. Is there a quick way to get the maximum key value in the associative
3
2745
by: pbali | last post by:
Hi, I am using PHP 5.1 and MySQL. I have a result set obtained by executing PDO:: query. I want to create an XML file by using this result set. The XML file will contain column names as XML node name and column values as node values. $orders = $db->query($sql); if (!empty($orders)) {
15
1567
by: James Black | last post by:
If you go to http://dante.acomp.usf.edu/HomeworkAssistant/index.php you will see my code. Type in: s = a + b and hit tab, and you will see the extra words. How do I remove these? Here is a snippet of my code: var myvalue = targ.value;
41
4966
by: Rene Nyffenegger | last post by:
Hello everyone. I am not fluent in JavaScript, so I might overlook the obvious. But in all other programming languages that I know and that have associative arrays, or hashes, the elements in the hash are alphabetically sorted if the key happens to be alpha numeric. Which I believe makes sense because it allows for fast lookup of a key.
11
2956
by: Bosconian | last post by:
I'm trying to output the contents of an array of associative arrays in JavaScript. I'm looking for an equivalent of foreach in PHP. Example: var games = new Array(); var teams = new Array(); teams = "Lakers";
9
2399
by: Jerim79 | last post by:
Here it is: <?php if($_SERVER=='POST'){ $Number=$_POST; $Email=$_POST; $Number2=0; $error=0;
11
1607
by: SM | last post by:
I have a couple of arrays that represent different categories. One array per category. The arrays contain names of photos. The arrays look like this: $cat_1 = array('moonlight.jpg'', shadow.jpg', 'luna.jpg'); $cat_2 = array(...); $cat_3 = array(...); $cat_4 = array(...); Then, i want to create a thumbnail with all the photos like this:
0
8787
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8697
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9289
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9158
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9060
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5939
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4454
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4712
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.