AlloyImage icon indicating copy to clipboard operation
AlloyImage copied to clipboard

Array.prototype.del 导致for 异常

Open RelicOfTesla opened this issue 10 years ago • 2 comments

Array.prototype.del = function(){ console.log('aa'); } var a = new Array(); a.push(1); for(var k in a){ console.log(k); }

输出 0 del

导致数组遍历异常

RelicOfTesla avatar Oct 21 '15 09:10 RelicOfTesla

  1. 既然是数组为何用for in遍历
  2. 使用for in要检查hasOwnProperty

will- avatar Oct 23 '15 17:10 will-

这是因为定义的del是可枚举的。可以换种方法定义del,而不用修改for in,

Object.defineProperty(
   Array.prototype,"del",{
      set: function (e) {},
      get: function () {
         return function(e)
         {
            e.sort(function (e, t) {return e - t;});
            var t = this.concat([]);
            for (var n = e.length - 1; n >= 0; n--)
               t = t.slice(0, e[n]).concat(t.slice(e[n] + 1));
            return t;
         }
      },
      enumerable: false,
      configurable: false
   }
);

关键是enumerable:false; 用这段代码,直接替换alloyimage.base.js或者alloyimage.js中开头的那个del的定义就可以避免后面使用for in出现问题。

HexagonCarbon avatar Sep 22 '17 02:09 HexagonCarbon