获取任何对象JavaScript的所有方法
我们需要编写一个程序(函数),该程序接受一个对象引用并返回存在于该对象上的所有方法(成员函数)的数组。我们仅需要返回数组中的方法,而无需返回其他任何属性可能具有功能以外的类型的值。
我们将使用Object.getOwnPropertyNames函数
Object.getOwnPropertyNames()方法返回直接在给定对象上找到的所有属性(无论是否可枚举)的数组。然后,我们将过滤数组以仅包含数据类型“函数”的属性。
示例
const returnMethods = (obj = {}) => {
const members = Object.getOwnPropertyNames(obj);
const methods = members.filter(el => {
return typeof obj[el] === 'function';
})
return methods;
};
console.log(returnMethods(Array.prototype));输出结果
控制台中的输出将是-
[ 'constructor', 'concat', 'copyWithin', 'fill', 'find', 'findIndex', 'lastIndexOf', 'pop', 'push', 'reverse', 'shift', 'unshift', 'slice', 'sort', 'splice', 'includes', 'indexOf', 'join', 'keys', 'entries', 'values', 'forEach', 'filter', 'flat', 'flatMap', 'map', 'every', 'some', 'reduce', 'reduceRight', 'toLocaleString', 'toString' ]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短