开发者

How to detect circular structures?

For example, this code:

var a = {};
a.a = a;
JSON.stringify(a);

Will throw:

开发者_C百科
TypeError: Converting circular structure to JSON

My question is, how to detect a circular structure?


Crockford's JSON implementation does just that. It looks like it just keeps a list while traversing the object graph. The code is fairly easy to follow.


Here is function using native JSON detection

function isCircular (d) {
  try {JSON.stringify(d)}
  catch (e) {return true}
  return false
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜