"JavaScript 순환참조 안전 prettyPrint()"의 두 판 사이의 차이

잔글 (Jmnote님이 JavaScript 순환참조 안전 prettyPrint 문서를 JavaScript 순환참조 안전 prettyPrint() 문서로 이동했습니다)
24번째 줄: 24번째 줄:
// 테스트 코드
// 테스트 코드
const a = { name: "Alice", age: 25, nested: { hobby: "Reading" }, items: [1, 2, 3] };
const a = { name: "Alice", age: 25, nested: { hobby: "Reading" }, items: [1, 2, 3] };
const b = { ...a, ref: null };
const b = { name: "Alice", age: 25, nested: { hobby: "Reading" }, items: [1, 2, 3] };
b.ref = b; // 순환 참조 생성
b.ref = b; // 순환 참조 생성



2025년 2월 16일 (일) 14:50 판

1 개요

JavaScript 순환참조 안전 prettyPrint
function prettyPrint(obj) {
    const format = (obj, depth = 0, seen = new WeakSet()) => {
        if (obj === null) return 'null';
        if (typeof obj !== 'object') return String(obj);
        if (seen.has(obj)) return '[Circular]';

        seen.add(obj);
        const indent = '  '.repeat(depth);
        const entries = Array.isArray(obj)
            ? obj.map((v, i) => `[${i}] ${format(v, depth + 1, seen)}`)
            : Object.entries(obj).map(([k, v]) => `${k}: ${format(v, depth + 1, seen)}`);

        return `${Array.isArray(obj) ? `Array(${obj.length})` : 'Object'} {\n` +
            entries.map(e => `${indent}  ${e}`).join('\n') + `\n${indent}}`;
    };

    console.log(format(obj));
}

// 테스트 코드
const a = { name: "Alice", age: 25, nested: { hobby: "Reading" }, items: [1, 2, 3] };
const b = { name: "Alice", age: 25, nested: { hobby: "Reading" }, items: [1, 2, 3] };
b.ref = b; // 순환 참조 생성

prettyPrint(a);
prettyPrint(b);

2 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}