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.

Tito
  • 722
  • 4
  • 26
  • 55
  • If you can modify the libraries you are using, you should add `if (!someArray.hasOwnProperty(i)) continue;` in these for loops. See here: http://stackoverflow.com/q/2040042/995958 – lorenzo-s Dec 05 '16 at 08:38
  • `for(i in someArray) if (someArray.hasOwnProperty(i)) {/* your code */}` – ixpl0 Dec 05 '16 at 08:39
  • Related: [Why is using “for…in” with array iteration a bad idea?](http://stackoverflow.com/q/500504/4642212) – Sebastian Simon Dec 05 '16 at 08: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. – Tito Dec 05 '16 at 12:21

1 Answers1

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);
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • 1
    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()`. – Redu Dec 05 '16 at 11:02