1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| 也称 ‘枚举’ 应该用在非数组对象的遍历上 不推荐用来循环数组(数组也是对象 但是 for-in中 属性列表的顺序是不能保证的)
值得说明的是 我们平常老是忽略一个很重要的方法 hasOwnProperty() 遍历对象属性的时候可以过滤掉从原型链上下来的属性
var man = { hands:2, legs:2, heads:1 }
if (typeof Object.prototype.clone === 'undefined'){ Object.prototype.clone = function(){ //。。。。 } }
// 为了避免枚举 出现clone方法 for (var i in man) { // 方式一 过滤原型属性 if (man.hasOwnProperty(i)) { // console.log(i, "1:", man[i]); } // 方式二 取消Object。prototype上的方法 if (Object.prototype.hasOwnProperty.call(man,i)){ // console.log(i, "1:", man[i]); } //或者 避免长属性查找 var hasOwn = Object.prototype.hasOwnProperty; if (hasOwn.call(man,i)){ // console.log(i, "1:", man[i]); } }
|