1 개요[ | ]
- JavaScript 순환참조 안전 prettyPrint
JavaScript
Copy
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);
▶ | Object {
name: Alice
age: 25
nested: Object {
hobby: Reading
}
items: Array(3) {
[0] 1
[1] 2
[2] 3
}
} |
▶ | Object {
name: Alice
age: 25
nested: Object {
hobby: Reading
}
items: Array(3) {
[0] 1
[1] 2
[2] 3
}
ref: [Circular]
} |
2 같이 보기[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.
- 분류 댓글:
- JavaScript (13)
HTML textarea 자동 높이 조절 ― …JavaScript 랜덤 한글 ― JmnoteJavaScript 랜덤 한글 ― JmnoteJavaScript 랜덤 한글 ―Pinkcrimson
JavaScript 랜덤 한글 ― MywikierJavaScript 변수 ― Nathan on zetawikiJavaScript 변수 ― John JeongJavaScript 변수 ― SotoZeroClipboard 사용하기 ― LilisZeroClipboard 사용하기 ― Jmnote자바스크립트 HTML 테이블 행 추가/삭제 ― Pilming자바스크립트 HTML 테이블 행 추가/삭제 ― Jmnote자바스크립트 웹페이지 읽기 ― …