原因:js使用原型链实现方法时,这个方法默认是可迭代的,所以在遍历时就会被遍历出来,
例:
Array.prototype.remove = function(n){return this.slice(0,n).concat(this.slice(n+1,this.length));}var cc = ["cccaaaa","ccccccccccc"];for(var key in cc){console.log(key,cc[key]);}
输出结果是:
解决方案:
使用Object.defineProperty方法设置对象的属性
Array.prototype.remove = function(n){return this.slice(0,n).concat(this.slice(n+1,this.length));}Object.defineProperty(Array.prototype,"remove",{enumerable:false,});var cc = ["cccaaaa","ccccccccccc"];for(var key in cc){console.log(key,cc[key]);}
输出结果:
或者是对于对象本身设置
var obj = {};obj.test = function(){console.log("ccccccccccc");};obj.age = 15;for(var key in obj){console.log(key,obj[key]);}
输出结果:
设置test方法不被迭代
var obj = {};obj.test = function(){console.log("ccccccccccc");};obj.age = 15;Object.defineProperty(obj,"test",{enumerable:false,});for(var key in obj){console.log(key,obj[key]);}
输出结果: