我们都知道数组上的在循环中是绝对邪恶。尽管如此,它们仍然经常被使用,所导致的错误很难跟踪,特别是当发生依赖于浏览器的事件时--例如,由于indexOf-shims等原因。
因此,我编写了这个简单的代码片段,它为Array.prototype上的“Array.prototype”属性添加了一个可枚举的getter (不在生产代码中使用):
Object.defineProperty(Array.prototype, "error", {
enumerable: true,
get: function() {
if (this === Array.prototype) // that looks OK
return undefined;
if (window.confirm("Somebody who coded the site you're viewing runs through an Array with a for-in-loop.\nShame on him!\n\nDo you want to raise an Error to trace the origin?"))
throw new SyntaxError("Array traverse with for-in-loop, touching Array.prototype's 'error' property :-)");
}
});您可以将其添加为所有域的greasemonkey脚本,并且几乎每个站点都会看到警报:-)其中大多数是由对jQuery.extend的调用引起的,参数有问题。
我现在的问题是:是否存在合法的“错误”循环,或者其他导致假阳性警报的情况?
我想知道这将如何影响我的代码的有用性。
发布于 2012-08-02 17:57:05
是。合法性往往是主观的,但是..。
例如,我可能有一个稀疏数组,其中我只在带有数据的索引处设置了值:
var a = [];
a[123123] = "foo";
a[1233123] = "bar";如果我想迭代在这个数组中定义的元素,那么我将使用for...in构造。即使我对其进行了防御性编码,您的脚本仍然会触发(假阳性).
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
// this is a legitimate array element
}
}更多信息和意见请参见为什么在数组迭代中使用"for...in“是个坏主意?。
https://stackoverflow.com/questions/11507509
复制相似问题