定义
Object.keys
定义:返回一个对象可枚举属性的字符串数组;
Object.getOwnPropertyNames
定义:返回一个对象可枚举、不可枚举属性的名称;
属性的可枚举性、不可枚举性
定义:可枚举属性是指那些内部 “可枚举” 标志设置为 true 的属性,对于通过直接的赋值和属性初始化的属性,该标识值默认为即为 true,对于通过 Object.defineProperty 等定义的属性,该标识值默认为 false。
例子
var obj = { "prop1": "v1" }; Object.defineProperty(obj,"prop2",{ value: "v2",writable: false }); console.log(Object.keys(obj).length); //output:1 console.log(Object.getOwnPropertyNames(obj).length); :2 console.log(Object.keys(obj)); //output:Array[1] => [0: "prop1"] console.log(Object.getOwnPropertyNames(obj)); :Array[2] => [0: "prop1",1: "prop2"]
内置的判断,访问和迭代方法
功能 | 可枚举 | 可枚举、不可枚举 |
判断 |
propertyIsEnumerable
|
in/hasOwnProperty |
访问 | Object.keys | Object.getOwnPropertyNames |
迭代 | for..in.. | Object.getOwnPropertyNames |
实战
true }); console.log(obj.hasOwnProperty("prop1")); output: true console.log(obj.hasOwnProperty("prop2")); output: true console.log(obj.propertyIsEnumerable("prop1")); output: true console.log(obj.propertyIsEnumerable("prop2")); output: false console.log('prop1' in obj); output: true console.log('prop2' output: true for (var item in obj) { console.log(item); } output:prop1 Object.getOwnPropertyNames(obj)) { console.log(Object.getOwnPropertyNames(obj)[item]); } ouput:[prop1,prop2]
相关链接
Object.hasOwnProperty()
Object.propertyIsEnumerable()
Object.getOwnPropertyNames()
Object.keys()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。