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:
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.
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));
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With