js异常处理:

当代码执行到 console.info('listElementClick = ' + JSON.stringify(info)); 时抛出:Converting circular structure to JSON

大概翻译就是:转换循环结构到JSON格式失败。

这是因为:

This would be the case with DOM nodes, which have circular references, even if they are not attached to the DOM tree. Each node has an ownerDocument which refers to document in most cases. document has a reference to the DOM tree at least through document.body and document.body.ownerDocument refers back to document again, which is only one of multiple circular references in the DOM tree.

内部结构例如:

var a = {};
a.b = a;

类似递归,自己内部指向自己,这样JSON.stringify()是没办法处理的。针对这种情况,处理如下:

function censor(censor) {
        var i = 0;
        return function(key, value) {
            if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value)
                return '[Circular]';
            if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
                return '[Unknown]';
            ++i; // so we know we aren't using the original object anymore
            return value;
        }
    }


console.info('listElementClick = ' + JSON.stringify(info, censor(info)));

猜你喜欢

转载自blog.csdn.net/fgx_123456/article/details/80063723

相关文章