Fork me on GitHub

JavaScript中Object.keys、Object.getOwnPropertyNames区别

定义

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);    //output:2

console.log(Object.keys(obj));           //output:Array[1] => [0: "prop1"]
console.log(Object.getOwnPropertyNames(obj));    //output:Array[2] => [0: "prop1", 1: "prop2"]

 

内置的判断,访问和迭代方法

功能 可枚举 可枚举、不可枚举
判断
propertyIsEnumerable
 in/hasOwnProperty
访问  Object.keys  Object.getOwnPropertyNames
迭代  for..in..  Object.getOwnPropertyNames

 

 

 

 

 

 

 

 

实战

var obj = { "prop1": "v1" };
Object.defineProperty(obj, "prop2", { value: "v2", writable: 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' in obj);    //output: true

for (var item in obj) {
    console.log(item);
}
//output:prop1

for (var item in Object.getOwnPropertyNames(obj)) {
    console.log(Object.getOwnPropertyNames(obj)[item]);
}
//ouput:[prop1,prop2]

 

相关链接

Object.hasOwnProperty()
Object.propertyIsEnumerable()
Object.getOwnPropertyNames()
Object.keys()

属性的可枚举性和所有权 

 

posted @ 2018-01-19 18:19  磊哥|www.javacn.site  阅读(2354)  评论(0编辑  收藏  举报