1

Mootools is overridding the Array prototype, and the problem is that this prototype and I have an external .js (a library that I can't modify manually) that iterates using for(i in someArray) and it is throwing exception, since now Array has more properties. Any ideas of how to overcome this problem ? I was thinking about removing those properties from array on the Mootools library itself, but it seems is not that easy.

4
  • If you can modify the libraries you are using, you should add if (!someArray.hasOwnProperty(i)) continue; in these for loops. See here: stackoverflow.com/q/2040042/995958 Commented Dec 5, 2016 at 8:38
  • for(i in someArray) if (someArray.hasOwnProperty(i)) {/* your code */} Commented Dec 5, 2016 at 8:39
  • Related: Why is using “for…in” with array iteration a bad idea? Commented Dec 5, 2016 at 8:42
  • I know is a bad practice, but this is a javaScript file from built-in SharePoint, it is defined on the sp.ribbon.js to be more specific. Somebody in Microsoft had the idea to iterate on arrays in this way. Commented Dec 5, 2016 at 12:21

1 Answer 1

3

First of all, you should use a regular for(var i=0; i < arr.length; i++) { var el = arr[i]; } loop on arrays.

If you really need for..in and you are working in modern browsers, then you can modify the modification to the prototype to make it non-enumerable.

//Logger function
function logArray(arr) {
    console.log("--TEST-START--");
    for (var i in arr) {
      console.log(arr[i])
    }
    console.log("--TEST-END--");
  }
  //Modify prototype
Array.prototype.a = {
  b: 0
};
//List to test against
var list = [1, 2, 3, 4];
//Log initial list
logArray(list);
//Modify prototype modificiation
Object.defineProperty(Array.prototype, 'a', {
  enumerable: false
});

//Log initial list
logArray(list);

Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is the right solution yet I would expect mootools to do this in the first place when they are adding new methods to the Array.prototype().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.