1

This is the piece code to show my question:

    var data=[];
    for(var pro in data) {
        console.log('Property: '+pro);
    }
    Array.prototype.Dummy=function() {
    };
    for(var pro in data) {
        console.log('Property:'+pro);
    }

I expect the 2 for in statements behave the same, the first prints nothing, reasonable, but the second one will list 'Dummy' only as the array's property, even Array has lots of buildin methods.

The user defined method is different from build in, why?

The reason I ask this question is that I use 3 party libraries, if I extend buildin data types(like Array, Date ect.), I'll potentially modify what their for in statements do.

diwatu
  • 5,641
  • 5
  • 38
  • 61
  • 4
    Don't use `for..in` to iterate arrays – Phil Jun 30 '21 at 01:13
  • 3
    user `for..of` in arrays. The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties. So it will includes the `Dummy` property also – DecPK Jun 30 '21 at 01:14
  • 3
    "*if I extend buildin data types*" - just don't do that. Not so much because of enumerations (there are ways around that, see the duplicate, and properly written libraries should know how to iterate arrays), but because of the risk of collisions, which would severely limit your choice of libraries in the future. – Bergi Jun 30 '21 at 01:22

0 Answers0