这个for-in循环检测片段是否会产生不必要的误报?

Ber*_*rgi 6 javascript loops

我们都知道阵列上的for-in-loops 绝对是邪恶的.尽管如此,它们经常被使用,并且导致的错误很难追查,特别是当发生依赖浏览器时,例如因为indexOf-shims等.

所以,我编写了这个简单的代码段,它为" error"属性添加了一个可枚举的getter Array.prototype(不用于生产代码):

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 :-)");
    }
});
Run Code Online (Sandbox Code Playgroud)

您可以将它添加为所有域的greasemonkey脚本,并且您将在几乎每个站点上看到警报:-)其中大多数是由调用jQuery.extend可疑参数引起的,顺便说一句.

我现在的问题是:是否有任何合理的"错误"循环任何其他导致误报警报的情况?

我想知道这将如何影响我的代码的有用性.

Ste*_*ell -1

是的。合法性往往是主观的,但是......

举个例子,也许我有一个稀疏数组,我只在带有数据的索引处设置值:

var a = [];
a[123123] = "foo";
a[1233123] = "bar";
Run Code Online (Sandbox Code Playgroud)

如果我想迭代在此数组中定义的元素,那么我将使用该for...in构造。即使我防御性地对其进行编码,您的脚本仍然会触发(误报)......

for (var prop in a) {
  if (a.hasOwnProperty(prop)) {
    // this is a legitimate array element
  }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅为什么在数组迭代中使用“for...in”是一个坏主意?获取更多信息和意见。

  • 不,防御性编码循环(这很好)永远不会访问“a[prop]”,其中“prop”是“error”,因此它不会引发异常。 (3认同)