JavaScript 如何从对象的可枚举属性中获取函数属性名的数组
可枚举属性: 可以使用for..in循环或Object.keys()方法进行迭代的对象的所有属性都被称为可枚举属性。
在本文中,我们将看到如何获取一个对象的可枚举函数的数组。可以通过以下两个步骤实现。
- 使用Object.keys()方法,我们可以获取包含对象的所有可枚举属性(包含函数和数据成员)的数组。
语法:
Object.keys(object_name)
- 然后,我们可以使用Array filter()方法过滤上述获取到的数组,使其只包含可枚举函数名(排除所有数据成员)。
语法:
new_arr = arr_name.filter((element) => {.....})
在下面的示例中,我们使用了Object.defineProperty()方法来创建一个非可枚举属性。
示例:
Javascript
<script>
// Person object has name, age, salary
// and print properties
// Except salary, all properties are enumerable
let Person = {
name: "Mahesh",
age: 25,
print: function () {
console.log(`{this.name}{(this, age)}`);
},
};
// salary- non enumerable property
Object.defineProperty(Person, "salary", {
value: "Rs. 50,000",
enumerable: false,
});
// greeting- non enumerable function
Object.defineProperty(Person, "greeting", {
value: function () {
console.log("Welcome to GFG");
},
enumerable: false,
});
// arr contains all the enumerable
// properties of Person
let arr = Object.keys(Person);
// functionsArr contains enumerable
// function properties of Person.
// typeof returns an string representing
// data type.
// Using filter() method to filter the array
let functionsArr = arr.filter((key) => {
return typeof Person[key] === "function";
});
console.log(arr);
console.log(functionsArr);
</script>
输出:
输出:
["name", "age", "print"]
["print"]
说明:
在上面的代码中,我们有一个名为Person的对象,它有3个数据成员(姓名,年龄和工资)和2个函数(’print’和’greeting’)。其中工资数据成员和问候函数是不可枚举的属性。
Property | Type | Enumerability |
---|---|---|
name | variable | enumerable |
age | variable | enumerable |
salary | variable | non-enumerable |
function | enumerable | |
greeting | function | non-enumerable |
在这里,’print’是唯一可枚举的函数。使用 Object.keys(Person) 我们得到一个包含所有可枚举属性的数组,即["name", "age", "print"]
。
然后我们使用 Array.filter() 方法过滤掉所有变量,这样数组中只有函数属性名,即["print"]
。