返回课程

排除反向引用

重要性: 5

在简单的循环引用情况下,我们可以通过名称排除序列化中出现问题的属性。

但有时我们不能只使用名称,因为它可能同时用于循环引用和普通属性。因此,我们可以通过其值来检查属性。

编写 replacer 函数来将所有内容字符串化,但删除引用 meetup 的属性。

let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  occupiedBy: [{name: "John"}, {name: "Alice"}],
  place: room
};

// circular references
room.occupiedBy = meetup;
meetup.self = meetup;

alert( JSON.stringify(meetup, function replacer(key, value) {
  /* your code */
}));

/* result should be:
{
  "title":"Conference",
  "occupiedBy":[{"name":"John"},{"name":"Alice"}],
  "place":{"number":23}
}
*/
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  occupiedBy: [{name: "John"}, {name: "Alice"}],
  place: room
};

room.occupiedBy = meetup;
meetup.self = meetup;

alert( JSON.stringify(meetup, function replacer(key, value) {
  return (key != "" && value == meetup) ? undefined : value;
}));

/*
{
  "title":"Conference",
  "occupiedBy":[{"name":"John"},{"name":"Alice"}],
  "place":{"number":23}
}
*/

这里我们还需要测试 key=="" 以排除第一次调用,因为在这种情况下 valuemeetup 是正常的。