JavaScript中的in


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2020/03/03/JavaScript%E4%B8%AD%E7%9A%84in/

摘要

本文主要讲述了:

  1. 作用

正文

作用

判断指定对象是否拥有指定属性。

示例:

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
49
50
51
52
53
54
var ageKey = Symbol('age');
var genderKey = Symbol('gender');

var foo = {
firstName: 'foo',
lastName: 'bar',
sayHello() {
return 'hello, world';
},
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName(fullName) {
var names = fullName.split(' ');
this.firstName = names[0];
this.lastName = names[names.length - 1];
},
[ageKey]: 18,
};

Object.defineProperty(foo, 'country', {
value: 'China',
});

Object.defineProperty(foo, genderKey, {
value: 'male',
});

// 不存在,输出false
console.log('lover' in foo);

// 存在,输出:true
console.log('firstName' in foo);

// 存在,输出:true
console.log('lastName' in foo);

// 存在,输出:true
console.log('sayHello' in foo);

// 存在,输出:true
console.log('fullName' in foo);

// 存在,输出:true
console.log('country' in foo);

// 存在,输出:true
console.log(ageKey in foo);

// 存在,输出:true
console.log(genderKey in foo);

// 存在,输出:true
console.log('toString' in foo);

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2020/03/03/JavaScript%E4%B8%AD%E7%9A%84in/


本文对你有帮助?请支持我


支付宝
微信