JavaScript:对象getOwnPropertyNames方法介绍及使用实例

602 阅读2分钟

在这篇博文中,将为您举例说明以下事项:

  1. 对象中getOwnPropertyNames的语法和例子
  2. Object.getOwnPropertyNames()与Object.key()方法之间的区别。
  3. 将Object的键转换为数组排序。
  4. 列出一个对象的所有功能 一个对象的长度

对象类中的getOwnPropertyNames()方法

getOwnPropertyNames()是javascript中Object类中的一个内置的方法。

在javascript中,每个类型都扩展了object,Array,一个扩展了Object的map都有getOwnPropertynames方法。

一个对象有可枚举的和不可枚举的属性。属性是属性,也是函数。

语法

Object.getOwnPropertyNames(Object) 

输入类型 - 接受一个对象作为输入参数
返回一个所有可枚举属性、不可枚举属性的数组,请查看对象属性指南
让我们看一个在对象中显示可枚举键的例子

const employee = {"name": "Franc","department":"sales"};  
console.log(Object.getOwnPropertyNames(employee));    
[ 'name', 'department' ]  

让我们使用Object.defineProperty()方法为一个存在的对象添加不可枚举的属性。

Object.defineProperty(employee,"address",{country:"India",enumerable:false})  
  
getOwnPropertyNames() method prints the array of enumerable and non-enumerable properties  
console.log(Object.getOwnPropertyNames(employee));    
[ 'name', 'department', 'address' ]  

Object.getOwnPropertyNames()与Object.key()方法之间的区别。

Object.key()只返回可枚举属性键的数组。Object.getOwnPropertyNames()返回可枚举和不可枚举属性键的数组。

const employee = {"name": "Franc","department":"sales"};  
Object.defineProperty(employee,"address",{country:"India",enumerable:false})  
console.log(Object.keys(employee));  
  
console.log(Object.getOwnPropertyNames(employee)); 

输出是

[ 'name', 'department' ]  
[ 'name', 'department', 'address' ]  

将Object键转换为数组排序

getOwnPropertyNames()返回键值数组。
,将返回的数组用排序或反向方法进行排序,并返回数组排序,如看到的例子。

console.log(Object.getOwnPropertyNames(employee));    
console.log(Object.getOwnPropertyNames(employee).sort()); 

输出是

  
  
[ 'name', 'department', 'address' ]  
[ 'address', 'department', 'name' ]  

让我们来看看一个例子,通过排序键的顺序,将对象转换成数组的值

Object.getOwnPropertyNames(employee).sort().forEach(function(element){  
         console.log((employee[element]));  
      })  

列出一个对象的所有功能

一个数组是一个对象,这个例子使用getOwnPropertyNames()方法打印出一个数组的所有功能或方法。

console.log(Object.getOwnPropertyNames(Array));    
//[ 'length', 'name', 'prototype', 'isArray', 'from', 'of' ]  
  
console.log(Object.getOwnPropertyNames(Array).filter(function (key) {  
    return typeof Math[key] === 'function';  
}));  
//[ 'isArray', 'from', 'of' ]  

一个对象的属性的长度

getOwnPropertyNames()返回一个对象的属性数组,对一个对象调用length可以得到数组的长度。

console.log(Object.getOwnPropertyNames(employee).length);  //3