我是靠谱客的博主 清脆薯片,这篇文章主要介绍JS获取对象属性名小结,现在分享给大家,希望可以做个参考。

JS获取对象属性名小结
最近面试遇到问如何获取对象全部属性名的方法,总结一下:

对象属性类型分类:

1.ESMAScript分类

数据类型 又分为可枚举和不可枚举类型
访问器类型
2.上下文分类

原型属性
实例属性
1.列举自身但不包括原型的可枚举属性名 Object.keys(obj)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 遍历对象 function Person(name, age) { this.name = name; this.age = age; } Person.prototype.demo = function() {}; let cj = new Person('cj', 25); // 通过Object.defineProperty定义一个不可枚举属性 Object.defineProperty(cj, 'weight', { enumerable:false }) // enumerable = true // console.log(Object.keys(cj)) // name age // enumerable = false // console.log(Object.keys(cj)) // name age weight

2.列举包括自身不可枚举但不包括原型的属性名

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Object.getOwnPropertyNames(obj) function Person(name, age) { this.name = name; this.age = age; } // 设置原型属性 Person.prototype.demo = function() {}; let cj = new Person('cj', 25); // 通过Object.defineProperty定义一个不可枚举属性 Object.defineProperty(cj, 'weight', { enumerable:false }) // 获取属性名 console.log(Object.getOwnPropertyNames(cj)) // name age weight

3.获取自身和原型链上的可枚举属性 for in 返回的顺序可能与定义顺序不一致

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function Person(name, age) { this.name = name; this.age = age; } // 设置原型属性 Person.prototype.demo = function() {}; Object.prototype.j = 1 let cj = new Person('cj', 25); // 通过Object.defineProperty定义一个不可枚举属性 Object.defineProperty(cj, 'weight', { enumerable:false }) let props = [] for(prop in cj){ props.push(prop) } console.log(props) //name age weight j

4.获取自身Symbol属性 Object.getOwnPropertySymbols(obj)

复制代码
1
2
3
4
5
6
7
8
9
10
let obj = {}; // 为对象本身添加Symbol属性名 let a = Symbol("a"); obj[a] = "localSymbol"; // 为对象原型添加Symbol属性名 let b = Symbol("b") Object.prototype[b] = 111 let objectSymbols = Object.getOwnPropertySymbols(obj); console.log(objectSymbols); //Symbol(a)

5.获取自身包括不可枚举和Symbol属性名,但不包括原型 Reflect.ownKeys(obj)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 遍历对象 function Person(name, age) { this.name = name; this.age = age; } Person.prototype.demo = function() {}; let s = Symbol('s') let cj = new Person('cj', 25); // 通过Object.defineProperty定义一个不可枚举属性 Object.defineProperty(cj, 'weight', { enumerable: false }) cj[s] = 1 let a = Symbol('a') Object.prototype[a] = 1 console.log(Object.getOwnPropertyNames(cj)) //name age weight console.log(Reflect.ownKeys(cj)) //name age weight Symbol(s)

最后

以上就是清脆薯片最近收集整理的关于JS获取对象属性名小结的全部内容,更多相关JS获取对象属性名小结内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部