used to be able to do this without any problems:
for (data in dataArray) { // do some stuff };
now, it suddenly is iterating through this __proto__
array that got added to my dataArray
. where the hell did it come from? is this from using the MooTools library? it's breaking all my loops! :P now i have to do this instead:
for (var i=0; i < dataArray.length; i++) { // do some stuff };
the thing i DO NOT get is why this works... does __proto__
not actually count as an array element? if not, then why does the first version not work like it used to, but the second does?
TIA for turning some lights on...
WR!
no. javascript is prototypical. it means that anything (any native type) can be extended by modifying its prototype. eg, if you want to add a new method that allows you to iterate through any array you may later create, you'd do:
Array.prototype.each = function(callback) {
// this == the array. code here...
return this;
};
this means any array created will support .each after: [].each(function(el) {});
. and yes, mootools is a heavily prototypical framework AT THE MOMENT. things are changing with mootools milk, which goes AMD - hence without extending natives...
ultimately, though, in javascript everything inherits from the Object native through the prototype chain.
as for Array, it's not really a proper Array Type - in javascript, it's more like an Object with array-like properties. which brings me to why you have the problem you have:
for (var foo in obj)
is actually a way of looping Objects
- not Arrays
. it works on arrays as well, because they are kind of like Objects as I mentioned.
but it's the wrong thing to do, especially when you work with a prototypical framework or you are not sure of all the code you run and how it has affected the prototype chain. if you mean to use what is known as an 'associative array' in other languages, simply use an Object.
In mootools, you can use Object.each(function(value, key) {});
to iterate them.
Or: in your loop check to see if the item hasOwnProperty:
for (var data in dataArray) {
if (dataArray.hasOwnProperty(data)) {
// avoids working with prototype.
}
}