/**
 * JSON.stringify
 * 对象的循环引用导致报错
 * @param {*} object 
 * @returns 
 */
const replacer = (key, value, depth) => {
    // 设置处理的最大深度
    let depthMax = 10;
    // 检查当前处理的深度是否超过最大深度
    if (depth > depthMax) return '[Max Depth Exceeded]';

    // 函数
    if (typeof value === "function") return;
    // 处理数组
    else if (Array.isArray(value)) {
        let result = [];
        for (let index = 0; index < value.length; index++) result[index] = replacer(index, value[index], depth + 1);
        return result;
    }
    // 处理对象
    else if (typeof value === 'object' && value !== null) {
        let result = {};
        for (let prop in value) result[prop] = replacer(prop, value[prop], depth + 1);
        return result;
    }
    return value;
};

/**
 * 序列化
 * @param object 
 * @returns 
 */
const stringify = object => JSON.stringify(object, (key, value) => replacer(key, value, 0), 2);

文章作者: CaptainTwo
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 CaptainTwo
NodeJs JavaScript NodeJs JavaScript
喜欢就支持一下吧