"JavaScript hasCircularReference()"의 두 판 사이의 차이

1번째 줄: 1번째 줄:
==개요==
==개요==
;JavaScript hasCircularReference()
;JavaScript hasCircularReference()
<syntaxhighlight lang='javascript' run>
<syntaxhighlight lang='javascript' run>
function hasCircularReference(obj) {
function hasCircularReference(obj) {
36번째 줄: 37번째 줄:
}
}


// 테스트 코드
// 테스트 코드
// 테스트 코드
const a = { x: 1, y: 2 };
const a = { x: 1, y: 2 };

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

개요

JavaScript hasCircularReference()
function hasCircularReference(obj) {
    const seen = new WeakSet();
    const detect = obj => {
        if (obj && typeof obj === 'object') {
            if (seen.has(obj)) return true;
            seen.add(obj);
            return Object.values(obj).some(detect);
        }
        return false;
    }
    return detect(obj);
}

// 테스트 코드
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
b.z = b; // 순환참조 생성

console.log(hasCircularReference(a)); // false
console.log(hasCircularReference(b)); // true
function hasCircularReference(obj, seen = new WeakSet()) {
    if (obj && typeof obj === 'object') {
        if (seen.has(obj)) return true;
        seen.add(obj);
        for (let key in obj) {
            if (hasCircularReference(obj[key], seen)) return true;
        }
    }
    return false;
}

// 테스트 코드
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
b.z = b; // 순환참조 생성

console.log(hasCircularReference(a)); // false
console.log(hasCircularReference(b)); // true
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}