473,568 Members | 3,164 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 6690
> 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
11137
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
1534
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)...
6
2003
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...
3
2732
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
1555
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
4901
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
2926
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
2380
by: Jerim79 | last post by:
Here it is: <?php if($_SERVER=='POST'){ $Number=$_POST; $Email=$_POST; $Number2=0; $error=0;
11
1595
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
7601
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...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6274
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5217
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...
0
3651
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...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2099
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
931
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.