<分区>
我最近写了几个 JS 数组原型(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);
});
};
那里没有什么特别令人兴奋的。但后来我遇到了一些非常不寻常的事情。这是一个例子
var arr = [];
for (prop in arr) {
arr[prop].attrib = arr[prop].attrib.replaceAll('_', ' ', true);
}
一段看起来很无辜的代码,但它返回给我时出现了错误“undefined does not have method replaceAll - where replaceAll is my own String.prototype extension.
解决方案很简单——在操作 arr[prop] 之前发出
if ('string' == typeof(prop)) continue;
原因是 prop 也可以是 diff 或 udiff。所以,问题解决了,但这种行为确实让我措手不及,不得不进行额外的 typeof 测试听起来很笨拙。也许这里有人对原型(prototype)扩展会发生什么有更深入的了解?
我应该提一下,所有这些问题都发生在 Windows 上的 Chrome 中。