Javascript Console API에 대한 자세한 이해 및 사용

Patricia Arquette
풀어 주다: 2024-10-24 08:22:29
원래의
184명이 탐색했습니다.

제 글이 마음에 드셨다면 커피 한잔 사주시면 됩니다 :)
Understanding and Using Javascript Console API in Detail


콘솔 API는 특히 브라우저Node.js 메시지 인쇄 및 다양한 정보를 콘솔로 전송하는 데 사용됩니다. >. 하지만 콘솔 API를 올바르게 사용하기 위해서는 콘솔 API가 무엇인지 정확히 알아야 합니다.

이 글에서는

콘솔 API에 대해 설명하겠습니다. 콘솔 API는 객체입니다. 이 객체에는 키가 있습니다. 콘솔 메서드를 작성할 때 콘솔 객체의 키 값에 액세스합니다.


이제

콘솔 API에서 로그 메소드가 어떻게 작동하는지 로직을 이해할 수 있도록 직접 콘솔 객체를 코딩하여 설명하겠습니다.

const customConsole = {
    log: function(message) {
        const timestamp = new Date().toISOString();
        const output = `[${timestamp}] LOG: ${message}`;
        alert(output); // Displaying the output (replace with console.log in a real scenario)
    }
};

customConsole.log("Hello, this is a custom console log!");

로그인 후 복사
로그인 후 복사
코드를 읽어보세요. 코드에서 볼 수 있듯이

사용자 정의 콘솔 개체를 만들고 이 개체에 대한 키를 정의했는데 이 키의 값은 함수입니다. 그러다가 이 객체의 로그 키에 접근했습니다.


결과적으로 콘솔 API에는 '로그' 메소드만 있는 것이 아닙니다. 그럼 몇 명이나 있나요? 지금 바로 알아보세요.

Understanding and Using Javascript Console API in Detail

사진에서 볼 수 있듯이

콘솔 개체에는 두 개 이상의 키와 해당 키의 값이 있습니다. 이 값은 함수입니다.

콘솔 개체를 사용하여 이러한 기능에 액세스할 수 있습니다.

console.error()
console.warn()
로그인 후 복사
로그인 후 복사
이제 이러한 기능 중 일부가 어떤 역할을 하는지 알아보겠습니다.


1. console.debug()

console.debug - 브라우저 콘솔에서 디버깅 목적으로 사용되는 JavaScript 함수입니다. 기본적으로 console.debug() 메소드의 출력은 Chrome 개발자 도구에 표시되지 않습니다.

:

function subtract(a, b) {
    console.debug("subtract function called:", { a, b });
    const result = a - b;

    if (result > 0) {
        console.debug("Result is positive.");
    } else if (result < 0) {
        console.debug("Result is negative.");
    } else {
        console.debug("Result is zero.");
    }

    return result;
}


let result = subtract(10, 5);  
로그인 후 복사
로그인 후 복사

출력 :

Understanding and Using Javascript Console API in Detail

console.debug() 메소드의 출력은 Chrome 개발자 도구에 표시되지 않습니다.


2. console.error()

JavaScript에서

오류 메시지를 콘솔에 출력하기 위해 사용하는 방법입니다. 오류가 발생할 때 디버깅을 용이하게 하는 데 사용됩니다. 메시지에는 빨간색 및 오류 아이콘과 같은 특수 형식이 표시될 수 있습니다.

:

async function fetchData(ıd) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${ıd}`);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log("posts data fetched successfully:", data);
        return data;

    } catch (error) {
        console.error(" error posts data :", error.message);
    }
}

fetchData(1);

로그인 후 복사
로그인 후 복사
데이터를 가져오는 동안 오류가 발생하면 다음과 같이 출력됩니다.

Understanding and Using Javascript Console API in Detail


3. console.warn()

JavaScript에서 잠재적인 문제나 주의가 필요한 상황을 콘솔에 출력하는 데 사용하는 방법입니다. 오류가 발생할 때 디버깅을 용이하게 하는 데 사용됩니다. 메시지에는 노란색 및 경고 아이콘과 같은 특수 형식이 적용될 수 있습니다.

:

const customConsole = {
    log: function(message) {
        const timestamp = new Date().toISOString();
        const output = `[${timestamp}] LOG: ${message}`;
        alert(output); // Displaying the output (replace with console.log in a real scenario)
    }
};

customConsole.log("Hello, this is a custom console log!");

로그인 후 복사
로그인 후 복사

4. console.dir()

console.dir() 메소드는 지정된 JavaScript 객체의 속성 목록을 표시합니다. 브라우저 콘솔에서 출력은 하위 개체의 콘텐츠를 볼 수 있는 공개 삼각형이 있는 계층적 목록으로 표시됩니다.

:

console.error()
console.warn()
로그인 후 복사
로그인 후 복사

출력 :

Understanding and Using Javascript Console API in Detail


5. console.dirxml()

console.dirxml() 메소드는 지정된 XML/HTML 요소의 하위 요소에 대한 대화형 트리를 표시합니다. 요소로 표시할 수 없는 경우 JavaScript Object 보기가 대신 표시됩니다. 출력은 하위 노드의 콘텐츠를 볼 수 있는 확장 가능한 노드의 계층적 목록으로 표시됩니다.

:

function subtract(a, b) {
    console.debug("subtract function called:", { a, b });
    const result = a - b;

    if (result > 0) {
        console.debug("Result is positive.");
    } else if (result < 0) {
        console.debug("Result is negative.");
    } else {
        console.debug("Result is zero.");
    }

    return result;
}


let result = subtract(10, 5);  
로그인 후 복사
로그인 후 복사

출력 :

Understanding and Using Javascript Console API in Detail


6. 콘솔.assert()

console.assert() 메서드는 어설션이 false인 경우 콘솔에 오류 메시지를 씁니다. 주장이 사실이라면 아무 일도 일어나지 않습니다.

:

async function fetchData(ıd) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${ıd}`);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log("posts data fetched successfully:", data);
        return data;

    } catch (error) {
        console.error(" error posts data :", error.message);
    }
}

fetchData(1);

로그인 후 복사
로그인 후 복사

출력 :

Understanding and Using Javascript Console API in Detail


7. 콘솔.카운트()

console.count() 메소드는 count()에 대한 특정 호출이 호출된 횟수를 기록합니다.

:

  if (password.length < minLength) {
        console.warn("Warning: Password must be at least 8 characters long.");
        return false; 
    }
로그인 후 복사

출력 :

Understanding and Using Javascript Console API in Detail


결론

조건이 true가 아닌 경우 오류 메시지가 인쇄됩니다. 조건이 true이면 아무 것도 인쇄되지 않습니다.

위 내용은 Javascript Console API에 대한 자세한 이해 및 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!