码迷,mamicode.com
首页 > 其他好文 > 详细

in、Object.keys

时间:2019-10-18 16:01:30      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:fine   对象   键值   link   方法   body   comm   array   code   

for in

  • 会遍历对象、数组以及该对象原型链上可以枚举的属性
  • 返回的结果都是String类型
  • 在某些情况下,遍历数组的顺序可能是随机的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Array.prototype.getLength = function() {
return this.length;
};
var arr = ['a', 'b', 'c'];
arr.name = 'June';
Object.defineProperty(arr, 'age', {
enumerable: true,
value: 17,
writable: true,
configurable: true
});
for(var i in arr) {
console.log(i);
}

不推荐在数组中使用for in遍历

如果使用for in遍历对象,我们一般只需要该对象的属性,而不需要该对象原型链上的属性。这时我们可以用hasOwnProperty来筛选

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const person = {
name: 'mark',
sex: 'male'
};
Object.prototype.age = 20;
for (let i in person) {
console.log(i);
}
// name, sex, age
for (let j in person) {
if (person.hasOwnProperty(j)) {
console.log(j);
}
}
// name, sex
// 拓展,获取对象自身所有属性
console.log(Object.getOwnPropertyNames(person))
// [name, sex]

Object.keys

  • 返回对象自身可枚举属性所组成的数组
  • 不会遍历对象原型链上的属性以及symbol属性
  • 按顺序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function () {
this.name = 'June';
}
Person.prototype.getName = function() {
return this.name;
}
var person = new Person();
Object.defineProperty(person, 'age', {
enumerable: true,
value: 17,
writable: true,
configurable: true
});
console.log(Object.keys(person));
大专栏  in、Object.keysmment">// ['name', 'age']

如果需要对象所有属性名,推荐使用该方法

for of

  • 支持遍历Array、Array like Object(DOM NodeList、arguments),String、Map、Set等类型
  • 不支持遍历普通对象以及原型链上的属性
  • 遍历的结果为String类型的Value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 1. 不会遍历到对象属性及其原型属性
Array.prototype.getLength = function() {
return this.length;
};
var arr = ['a', 'b', 'c'];
arr.name = 'June';
Object.defineProperty(arr, 'age', {
enumerable: true,
value: 17,
writable: true,
configurable: true
});
for(let i of arr) {
console.log(i);
// a,b,c
}

// 2. 如果要遍历对象,可与 Object.keys 配合
var person = {
name: 'June',
age: 17,
city: 'guangzhou'
}
for(var key of Object.keys(person)) {
console.log(person[key]);
// June, 17, guangzhou
}

//拓展
Object.entries()会返回多个由对象属性Key和Value组成的数组
const arr = {
name: 'mike',
age: 18
};
console.log(Object.entries(arr));
// [['name', 'mike'], ['age', '18']]

// 3. 配合 entries 输出数组索引和值/对象的键值
var arr = ['a', 'b', 'c'];
for(let [index, value] of Object.entries(arr)) {
console.log(index, ':', value);
// 0:a, 1:b, 2:c
}
var obj = {name: 'June', age: 17, city: 'guangzhou'};
for(let [key, value] of Object.entries(obj)) {
console.log(key, ':', value);
// name:June,age:17,city:guangzhou
}

in、Object.keys

标签:fine   对象   键值   link   方法   body   comm   array   code   

原文地址:https://www.cnblogs.com/dajunjun/p/11698490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!