您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何以类似JSON的格式打印圆形结构?

如何以类似JSON的格式打印圆形结构?

JSON.stringify自定义替换器一起使用。例如:

// Demo: Circular reference
var circ = {};
circ.circ = circ;

// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(circ, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Duplicate reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection

在此示例中,替换器不是100%正确的(取决于您对“重复”的定义)。在以下情况下,将丢弃一个值:

var a = {b:1}
var o = {};
o.one = a;
o.two = a;
// one and two point to the same object, but two is discarded:
JSON.stringify(o, ...);

但是概念仍然存在:使用自定义替换器,并跟踪已解析的对象值。

其他 2022/1/1 18:16:40 有387人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶