PDA

View Full Version : Ext breaks Array iteration?



_Sergio_
21 Oct 2007, 11:14 AM
Hi!

I'm having a problem iterating associative arrays with ext enabled.
It seems Ext adds remove method to all arrays.

How should I iterate an array in a regular manner without adding additional checks?
I can't use for(var i=0; i<a.length; i++) as length is not valid property due to numbers used as keys.




var a = [];
a[7] = "val1";
a[8] = "val2";

for(var i in a) alert(i+'='+a[i]);


This outputs:


7=val1
8=val2
remove=function(B){
var A = this.indexOf(B);
if(A!=-1){
this.splice(A,1);
}
}



Tnx for any help in advance.

Animal
21 Oct 2007, 11:33 AM
This has been discussed many times. You are misunderstanding how to use Arrays.

If you use an Array as an Object, and use for...in, you are not iterating through the elements of the Array, you are iterating through the properties of that Object.

Use an integer for loop to iterate through an Array's elements.

_Sergio_
21 Oct 2007, 11:56 AM
Hi Animal,

Tnx a lot for your answer.
I'm searching through the threads, but since I'm am obviously a bit noobish, can you please help a bit? ;)



var cart = [];
cart[13] = {name:"Spoon" price:12};
cart[123] = {name:"Spoon" price:12};


How would you iterate through the products in the cart, they are indexed by product id?
Only way I know is for...in.

Tnx for helping! ;)

Animal
21 Oct 2007, 12:28 PM
You are using a hash, not an array, just with a key that happens to be numeric:



var cart = {};
cart[13] = {name:"Spoon" price:12};
cart[123] = {name:"Spoon" price:12};


And use for...in

_Sergio_
21 Oct 2007, 12:43 PM
Animal, tnx for your help!
Works as expected :D