Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why iteration over array shows my custom prototype functions as items?

Why creating custom prototype functions like:

Array.prototype.clone = function(){
    return JSON.parse(JSON.stringify(this));
}

is making them visible when iterating over a for loop?

For example: enter image description here

It's clear that I have an array with 7 arrays inside, but for some reason it is considering all my custom functions when inside the loop. Why? How can I prevent it?

OBS: I am applying to some sort of javascript contest, which takes my algorithm and plays against other players. This loop, is inside the runner, so please consider that changing the way the iterations are processed is not an option.

This is breaking the runner as it tries to execute some code with the columns thinking that my custom function are included on it.

However, looking at their code, I noticed that it is possible to prevent this from happening as they also edit/create Array.prototype functions.

like image 306
Patrick Bard Avatar asked Sep 01 '25 05:09

Patrick Bard


1 Answers

Don't use for...in loops to iterate over an array. for...in loops enumerate all of the properties of an object, and since your new prototype function is enumerable, it will be listed as well. The way to avoid this is to use array.hasOwnProperty, but why do that when you can iterate over the array correctly with a regular for loop? It'll be faster and use less code:

for (var i = 0; i < this.matrix.length; i++) {
    ...
}

To make your new function not appear when enumerating an object's properties, you need to make it not enumerable:

Object.defineProperty(Array.prototype, 'clone', {
    enumerable: false,
    value: function(obj) {
        return JSON.parse(JSON.stringify(obj));
    }
});
like image 55
Blender Avatar answered Sep 02 '25 17:09

Blender