views:

289

answers:

1

Hello,

Try running the code below:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
<script> b = jQuery.noConflict(true); </script>

<script src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.3/mootools-yui-compressed.js"&gt;&lt;/script&gt;

<script>

(function($){   

    $.a = function(){
     var x = [];
     for (l in x){
      console.log(l);
     }
    };




})(b);

b.a();




</script>

Even though x is empty, in console.log you will see some values. Why is this happening? Am at the end of my wit.

Can someone please suggest how to solve this problem.

+2  A: 

MooTools heavily extends the Array.prototype, and you are iterating your array with a for...in statement.

This statement is made to iterate over object properties, for Arrays a traditional for or while loop is recommended.

Why ? because the for...in statement crawls up the prototype chain as you noticed, also because the order of iteration is arbitrary, iterating over an array may not visit the elements in the numeric order.

However if you still want to iterate using this statement, you can make a check inside the loop, to ensure that the properties you will iterate, are present directly on the object, and not somewhere on the prototype chain, using the hasOwnProperty function:

var x = [];
for (l in x){
  if (x.hasOwnProperty(l)) {
    console.log(l);
  }
}
CMS
now thats a real headache, cause I am using hundreds of for loops.
Alec Smart
okay ive done that. what else does mootools extend? thats so annoying because am using jQuery in noConflict mode. How am I to control mootools?
Alec Smart
mootools extends lots of stuff, but usually that doesn't matter. You should be very wary about `for...in` whether you're using mootools or not. Certainly for array iteration you should always stick to the standard `for (var i= 0; i<array.length; i++)` loop.
bobince
yes but he needs the array key, which a normal loop won't give
Dimitar Christoff