PDA

View Full Version : [SOLVED]function appears in my array...?



sj137
3 Aug 2007, 5:41 AM
this may not be an ext issue, jus wondering if anyone else has encountered it...

i have an array like:



var myarray = [];

myarray.push('hello');
myarray.push('world');


myarray.length reads 2, however when i iterate through the array i get 3 values!

eg



var counter=0;

for (x in myarray){
console.log(myarray[x]);
counter++;
}

console.log(counter);


the result in firebug is as follows:

hello
world
function()
3

..!!! what is going on?

/:)

matjaz
3 Aug 2007, 7:29 AM
Your are iterating in incorrect way.
Iterating with for..in is for objects.
To iterate through array, you must use
for (var i=0, len=array.length; i<len; i++)or you can use Ext.each() (http://extjs.com/deploy/ext/docs/output/Ext.html#each).

Cause of this is Ext is adding some own functions to native Array class.

para
3 Aug 2007, 7:33 AM
The reason for it is that arrays have a 'remove' function automatically.
For many of my loops I use this.


for(var a in whatever) {
if(a=='remove'){continue;}
//Do your code here.
}

That being said, I do agree that using the .length is a better way to do it.

sj137
4 Aug 2007, 6:47 AM
excellent replies

cheers guys :D