I recently wrote a couple of extensions to the JS array prototype
Array.prototype.diff = function (a) {
return this.filter(function (i) {
return !(a.indexOf(i) > -1);
});
};
Array.prototype.udiff = function (a, b) {
var rslt = this.concat(b);
return rslt.filter(function (i) {
return !(a.indexOf(i) > -1);
});
};
Nothing terribly exciting there. But then I ran into something quite unusual. Here is an example
var arr = [];
for (prop in arr) {
arr[prop].attrib = arr[prop].attrib.replaceAll('_', ' ', true);
}
Quite an innocent looking piece of code but it came back to me with an error along the lines of "undefined does not have method replaceAll - where replaceAll is my own String.prototype extension.
The solution is simple - before manipulating arr[prop] just issue
if ('string' == typeof(prop)) continue;
The reason being that prop can also be diff or udiff. So, problem solved but this behavior did take me off my guard and having to do the additional typeof test does sound clumsy. Perhaps someone here has deeper insights into what happens with prototype extensions?
I should mention that all of these issues occured in Chrome on Windows.