// 遍历对象的可枚举属性 var obj = { name:‘Nicholas‘, job:‘engineer‘ }; Object.getPrototypeOf(obj).age = 33; //1.for-in for (var property in obj) { console.log(‘Name:‘ + property); console.log(‘Value:‘ + obj[property]); } //2.Object.keys() var properties = Object.keys(obj); var i,len; for (var i = 0; i < properties.length; i++) { console.log(‘Name:‘ + properties[i]); console.log(‘Value:‘ + obj[properties[i]]); } // 区别:for-in会遍历原型属性而Object.keys()只返回自有(实例)属性。 // 对for-in进行以下处理,则for-in等同于Object.keys() for (var property in obj) { if(obj.hasOwnProperty(property)) { console.log(‘Name:‘ + property); console.log(‘Value:‘ + obj[property]); } }
时间: 2024-10-07 05:05:56