1.从 ECMAScript 5 开始,有三种原生的方法用于列出或枚举对象的属性:
for...in:该方法依次访问一个对象及其原型链中所有可枚举的属性
let obj = {a:1,b:2,c:3};for(let iinobj) { console.log("obj."+ i +" = "+ obj[i]);}// "obj.a = 1"// "obj.b = 2"// "obj.c = 3"
Object.keys(O):该方法返回一个数组,它包含了对象O自身的所有可枚举属性的名称
letobj = {0:"a",1:"b",2:"c"};console.log(Object.keys(obj)); //["0","1","2"]
Object.getOwnPropertyNames(O):该方法返回一个数组,它包含了对象O所有拥有的属性(包括不可枚举)的名称
varobj =Object.create({}, {getFoo: {value:function(){returnthis.foo; },enumerable:false}});obj.foo =1;obj.prototype = {a:1,b:2,c:3};console.log(Object.getOwnPropertyNames(obj).sort());//["foo", "getFoo", "prototype"]
console.log(Object.getOwnPropertyNames('asdfgc'));//["0","1","2","3","4","5","length"]
2.区别
如果你只要获取到可枚举属性,查看Object.keys或用for...in循环(还会获取到原型链上的可枚举属性,不过可以使用hasOwnProperty()方法过滤掉)
functionobject(){this.color ="red";}object.prototype = {a:1,b:2,c:3};varobj =newobject();for(varpropinobj) {console.log(prop);// "color" "a" "b" "c"}for(varpropinobj) {if( obj.hasOwnProperty(prop)){console.log(prop);// "color"} }console.log(Object.keys(obj));//["color"]
前端学习群:543761540 点击链接加入群【前端交流总群③】:https://jq.qq.com/?_wv=1027&k=47bGc0u