-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson3.js
More file actions
46 lines (35 loc) · 979 Bytes
/
json3.js
File metadata and controls
46 lines (35 loc) · 979 Bytes
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
let user = {
firstName: "san",
lastName: "zhang",
get fullName() {
return this.lastName + this.firstName
},
}
console.log(JSON.stringify(user));
//{"firstName":"san","lastName":"zhang","fullName":"zhangsan"}
/* JSON.stringify 发现参数对象有 toJSON 方法,
就直接使用这个方法的返回值作为参数,而忽略原对象的其他参数 */
let user2 = {
firstName: "san",
lastName: "zhang",
get fullName() {
return this.lastName + this.firstName
},
toJSON: function () {
return {
name: this.lastName + this.firstName
}
}
}
console.log(JSON.stringify(user2)); //{"name":"zhangsan"}
let date = new Date('2022-09-23');
console.log(date.toJSON());
console.log(JSON.stringify(date));
let obj3 = {
reg: /foo/
};
console.log(JSON.stringify(obj3));
RegExp.prototype.toJSON = RegExp.prototype.toString;
console.log(JSON.stringify(/foo/));
JSON.parse(1);
JSON.parse("bar");