Had a strange bug appear today. In our app, on one file, all the objects got a function attached, as if they were prototyped. We’re not prototyping our arrays but I’ve worked on other stuff where the arrays and objects had prototypes and when you did a for(this in that) loop the prototypes would be included as items and we had to filter them. So, two part question:
-
If you prototype your arrays will the index increase by + # of prototypes? So if array(a,b,c) has array.prototype.function(), would it’s index count be 3 or 4?
-
Should this be happening?
We’re thinking one of the jquery plugins we have is being all evil.
By “index count” I assume you mean
lengthproperty. In which case, the answer to your first question is “no.” Thelengthproperty is tied to the highest numerical index of an array. So, for instance, if you have the following code,arr.lengthwill be4:However, you referred to for-in loops, which have strange behavior in this situation. If we perform a for-in on
arr(from above), we get the following:As I mentioned, prototyped properties have no impact on the length:
However, they do impact for-in loops (under normal circumstances):
There are a few ways to get around this. First of all, you should really never be using for-in on array objects because of this kind of nonsense. But if you MUST do it for some reason, you should always protect your for-in loop using a
hasOwnProperty()filter, like so:Again, there’s no guarantee of ordering on for-in. So if
arrwas[1,1,1], you might getoutputas"201"(though it’s unlikely).Another option is to try and save yourself from others’ bad coding by using a feature of ES5 (if present) to protect your prototyped properties on the object level by setting them to be non-enumerable. You would do that like this:
I cannot stress enough that doing a for-in over an Array is a bad idea. In fact, I would tend to avoid for-in under pretty much all circumstances because you never know if someone out there wants to be a jerk and will toss this into the middle of their code: