473,597 Members | 2,092 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Javascript Array.push fix breaks for(var x in myarray)

In IE5 I am working with a lot of code that uses

Array.push()

as well as

for(var i in myArray) {}

Great - so I'm fixing the Array.prototype .push function for browsers
without it. That much works great. However as soon as I start
traversing arrays with for(... in ...) I end up with additional
elements at the end of the array.

A colleague said it was down to the added methods being seen as part of
the array , which to be sounds slightly strange!

Any ideas are welcome!

Thanks,

Andy.

Sep 22 '05 #1
3 3829
"Andrew Phillipo" <an************ @yahoo.co.uk> writes:
Array.push() .... for(var i in myArray) {}

Great - so I'm fixing the Array.prototype .push function for browsers
without it. That much works great. However as soon as I start
traversing arrays with for(... in ...) I end up with additional
elements at the end of the array.
Yes, the element "push".
A colleague said it was down to the added methods being seen as part of
the array , which to be sounds slightly strange!
Not really. The "for(..in.. )" construct iterates over all properties
of an object (not marked as DONT_ENUM). It's not restricted to arrays,
and does nothing special for arrays, so it will find the "push" property
you have added.
Any ideas are welcome!


Use "for(var i = 0; i < arr.length; i++) {" instead of "for(var i in array){".

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Sep 22 '05 #2
On 22/09/2005 17:46, Andrew Phillipo wrote:
In IE5 I am working with a lot of code that uses
[snip]
for(var i in myArray) {}
Well then, don't. Iterate over the array using the length property:

for(var i = 0, n = myArray.length; i < n; ++i) {
/* ... */
}

[snip]
[...] I end up with additional elements at the end of the array.


As you should. A for..in statement will walk over all enumerable
properties, which will include both user-defined properties (the array
elements) and methods.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Sep 22 '05 #3


Andrew Phillipo wrote:
In IE5 I am working with a lot of code that uses

Array.push()

as well as

for(var i in myArray) {}

Great - so I'm fixing the Array.prototype .push function for browsers
without it. That much works great. However as soon as I start
traversing arrays with for(... in ...) I end up with additional
elements at the end of the array.


No, for .. in does not traverse an array, it enumerates the properties
of any object, and enumeration might show methods as well as they are
simply function properties.

If you want to loop through an array in JavaScript use
for (var i = 0; i < myArray.length; i++) {
// access myArray[i]
}

Enumeration is useful for objects but even there you can of course run
into that trouble that someone for instance has added properties or
methods to Object.prototyp e. That is why you can find debates whether or
not someone writing a JavaScript library should add methods to
Object.prototyp e or not.

If you need enumeration you can distinguish methods with typeof checks e.g.

Object.prototyp e.someMethod = function () {}

var god = { name: 'Kibo', home: 'http://www.kibo.com/' };

var result = '';

for (var propertyName in god) {
result += propertyName + ': ' + (typeof god[propertyName]) + '\r\n';
}

alert(result);
In most implementations by now you can also use hasOwnProperty to find
out whether it is a property of the object itself or one in the
prototype chain:

Object.prototyp e.someMethod = function () {}

var god = { name: 'Kibo', home: 'http://www.kibo.com/' };

var result = '';

for (var propertyName in god) {
result += propertyName + ': ' + (typeof god[propertyName]) +
(god.hasOwnProp erty ? '; hasOwnProperty( "' + propertyName + '"): ' +
god.hasOwnPrope rty(propertyNam e) : '') + '\r\n';
}

alert(result);

But IE 5/Win with the JScript 5 it installs does not support
hasOwnProperty if recollection serves me right.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Sep 22 '05 #4

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

Similar topics

4
9599
by: 127.0.0.1 | last post by:
In there any mechanism to get a server side PHP variable, into a client side Javascript variable - without the value of the variable being visible in a view source ? -- Spam:newsgroup(at)craznar.com@verisign-sux-klj.com EMail:<0110001100101110011000100111010101110010011010110 11001010100000001100011011100100110000101111010011011100 1100001011100100010111001100011011011110110110100100000>
11
3509
by: Laphan | last post by:
Hi All I'm using .getRows() with a local var array instead of doing a recursive loop so that I'm being a good ASP newvbie and closing my object i/o's (the recordset in this case) as quick as possible. My problem is that I can't seem to use this to complete good effect because the IsArray statement doesn't seem to work with a local var array that has or has not been populated with the .getRows() property.
5
4114
by: VB Programmer | last post by:
I have a javascript calculator. How do I pass the value of the calculator result to another ASPX page so that I can right some VB.NET against the value? Thanks!
1
2487
by: gatejs | last post by:
In IE. If you use the back button, the resulting page will execute the javascript in the page again: In Firefox, whatever value a variable had is kept when you go back to it: var i=0; // after some interaction with this page, i=4 visit some link press the back button.
1
1597
by: diac | last post by:
Hello, I create and fill a variable in the Page_Load sub and then i need it in a javascript code. Of course the xxx variable is declared in the sub so that it is not available out of the sub. How can i fill the javascript variable with its content? ------------------------------------ Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Dim xxx As String = "xxx"
2
1653
by: runsun pan | last post by:
This has been puzzling me for a long time. Lets defined a global variable (not within any function) : var fff = function(){} This creates a global object that we can access via: alert(fff)
2
1234
by: medaps | last post by:
Hi, Is there a way to place php var with LF such as: $p="string1 \n string2" into: var j="<? echo $p ?>"; I am getting an error in j assigment: Unterminated string constant Thanks <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
1
1593
by: Ger | last post by:
My problem is related to this thread. I wrote an XML DOM parser. It parses the complete tree on IE, but it stops after the first downstream on FireFox, SeaMonkey and Opera. This is a simplified code that reproduces the issue: function PrintNode(node) { AddText("<b>"+node.nodeName+"</b>="+node.nodeValue+" ("+node.childNodes.length+" children)"); if (!node.hasChildNodes) return; AddText("<ul>"); var child=node.firstChild;...
1
1580
by: fran7 | last post by:
Hi, Anyone know how to solve the following, if I can describe it well enough. I have a database with interface. I have a webpage with javascript popups. the links are as follows <a href="http://www.site.com" id="tip297">name</a> in the head I have the external js file linked where all the ids are kept. they are like this var tip6 = '<img src="a/6.jpg"><div class="tp2">name</div>';
0
7965
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
7884
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
8270
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...
1
8029
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,...
0
8258
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6683
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5423
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
3880
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...
1
2394
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

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.