I have the following code in my web app's main JavaScript:
// uniq for arrays
if (!Array.prototype.getUnique) {
Array.prototype.getUnique = function () {
var u = {}, a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
}
It's a simple uniq
clone for javascript, monkeypatched into the basic Array class. (Not here to debate monkeypatching, flame elsewhere please...)
getUnique()
works as intended, but now whenever I iterate over an Array with a for...in
loop, an additional index called getUnique
is passed to the iterator body, and when this false n
is looked up, getUnique
's code is the value. (In other words: for...in
is looping over the array as it should, but appending a getUnique
as the last iteration)
What is going on here? There's another function monkeypatched in right above this one that works fine (indexOf()
) and does not appear in the iterator. Here is some example code that triggers this issue:
for (var r in result) {
//tags = tags + result[r]["tags"].split(" ").join(", ")
if (result[r]["tags"]) {
var newtags = result[r]["tags"].split(" ");
debug.log(newtags);
for (var n in newtags) {
debug.log("n is " + n);
tags.push(newtags[n]);
}
}
}
The debug output from this snippet looks like:
[14:22:26.090] [["camp", "furnitur", "wood"]]
[14:22:26.093] ["n is 0"]
[14:22:26.096] ["n is 1"]
[14:22:26.099] ["n is 2"]
[14:22:26.101] ["n is getUnique"]
What is going on here? Refactoring the monkeypatch and dropping it in a utility class is easy enough, but this is a really strange edge case to me. I have some ideas in my head about what is happening here, but those are just guesses. Can anyone explain?