Benjamin - 专注前端开发和用户体验

Javascript 属性的可枚举性和所有权

点滴Javascript Benjamin 2284℃ 0评论

日常开发中经常会遇到需要把json对象的key转换为数组的需求,今天来看看几种实现方式以及它们之间的区别。

一、基本对比

Method Description Detail
Object.keys 返回一个由给定对象的所有可枚举自身属性的属性名组成的数组 详细
Object.getOwnPropertyNames 返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性)组成的数组 详细
for…in The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.同时 还会遍历出该对象从其原型链上继承到的可枚举属性 详细

二、相关实例

实例一:枚举数组

var authors = ["Tolkien", "Lewis"];

// Outputs: ["0", "1"]
console.log(Object.keys(authors));

// Outputs: ["0", "1", "length"]
console.log(Object.getOwnPropertyNames(authors));

var res = [];

for(var key in authors) {
	res.push(key);
}
// Outputs: ["0", "1"]
console.log(res);

实例二:枚举对象属性及原型链上的属性

function User () {
	this.name = "Benjamin";
	this.url  = "http://www.zuojj.com";
}

User.prototype.sex = "male";

var user = new User();
//Outputs: User {name: "Benjamin", url: "http://www.zuojj.com", sex: "male"} 
console.log(user);

//Outputs: ["name", "url"] 
console.log(Object.keys(user));

//Outputs: ["name", "url"] 
console.log(Object.getOwnPropertyNames(user));

var res = [];
for(var key in user) {
	res.push(key);
}

//Outputs: ["name", "url", "sex"] 
console.log(res);

三、属性的可枚举性和所有权

Property enumerability and ownership – built-in methods of detection, retrieval, and iteration
Functionality Own object Own object and its prototype chain Prototype chain only
Detection
Enumerable Nonenumerable Enumerable and Nonenumerable
in and hasOwnProperty in and not propertyIsEnumerable hasOwnProperty
Not available without extra code Not available without extra code
Retrieval
Enumerable Nonenumerable Enumerable and Nonenumerable
Object.keys getOwnPropertyNames filtered to include properties when not passing propertyIsEnumerable getOwnPropertyNames
Not available without extra code Not available without extra code
Iteration
Enumerable Nonenumerable Enumerable and Nonenumerable
for..in filtered by hasOwnProperty Iterate over getOwnPropertyNames filtered to include properties when not passing propertyIsEnumerable Iterate over getOwnPropertyNames
Enumerable Nonenumerable Enumerable and Nonenumerable
for..in Not available without extra code Not available without extra code
Not available without extra code

四、兼容性问题

Object.getOwnPropertyNames(),Object.keys()是ES5规范的一部分,因此在IE8及以下版本浏览器不被支持。

喜欢 (1)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(1)个小伙伴在吐槽