开发者

Mootools Strange bug conflict with jQuery

开发者 https://www.devze.com 2022-12-08 08:25 出处:网络
Try running the code below: <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></script>

Try running the code below:

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

<script src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.3/mootools-yui-compressed.js"></script>
<script>
  (function($){  
    $.a = functi开发者_运维问答on(){
      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.


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);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号