[HTML, Javascript] JavaScript에 변수가 있는지 확인

이 기사에서는 변수가 정의 / 초기화되었는지 확인하는 여러 방법을 소개합니다. 아래의 모든 메서드에는 컴퓨터에서 실행할 수있는 코드 예제가 있습니다.

typeof연산자를 사용하여 JavaScript에 변수가 있는지 확인합니다

typeof 연산자는 변수가 정의/null인지 확인하지만 선언되지 않은 변수와 함께 사용하면ReferenceError를 발생시키지 않습니다.

예:

 
<!DOCTYPE html>  
<html>  
  
<head>  
    <title>  
        How to check if variable exists in JavaScript?
    </title> 
</head>  
          
<body style = "text-align:center;">  
      
    <h2 >  
        How to check if variable exists in JavaScript?
    </h2>  
              
    <p> 
        variable-name : Vatiable1 
    </p> 
  
    <button onclick="checkVariable()">  
        Check Variable
    </button>  
      
    <h4 id = "result" style="color:blue;"></h4> 
              
    <!-- Script to check existence of variable -->
    <script>  
       const checkVariable = () => { 
              
            let Vatiable1;  
            
            let result = document.getElementById("result"); 
            
            if (typeof Vatiable1 === 'undefined') { 
                result.innerHTML = "Variable is Undefined"; 
            } 
            else { 
                result.innerHTML = "Variable is defined and" 
                    + " value is " + Vatiable1; 
            } 
        } 
    </script>  
</body>  
 

예:

위와 동일한 html을 사용합니다.

 
<script>  
    const checkVariable = () => { 

        let Vatiable1 = "variable 1";  

        let result = document.getElementById("result"); 

        if (typeof Vatiable1 === 'undefined') { 
            result.innerHTML = "Variable is Undefined"; 
        } 
        else { 
            result.innerHTML = "Variable is defined and" 
                + " value is " + Vatiable1 ; 
        } 
    } 
</script>  

예:

위의 동일한 html을 사용하여 변수가 null인지 확인합니다.

 
 
<script>  
       const checkVariable = () => { 
              
            
            let Vatiable1 = null;  
            let result = document.getElementById("result"); 
            
            if (typeof Vatiable1 === 'undefined' ) { 
                result.innerHTML = "Variable is Undefined"; 
            } 
            else if (Vatiable1 === null){
              result.innerHTML = "Variable is null and not declared"; 
            }
            else { 
                result.innerHTML = "Variable is defined and" 
                    + " value is " + Vatiable1 ; 
            } 
        } 
    </script>  

if (varibale)문을 사용하여 JavaScript에 변수가 있는지 확인합니다

또한if 문을 사용하여 변수가undefined,null'',0,Nan, 및 false. 그러나typeof 연산자는undefined 또는null 만 확인합니다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

예:

위의 동일한 html을 사용합니다.

 
<script>  
    const checkVariable = () => { 

        //let Vatiable1;
        let Vatiable1 = null;  
        // let Vatiable1 = '';  
        let result = document.getElementById("result"); 
        if(Vatiable1){
            result.innerHTML = "Variable is defined and" 
                + " value is " + Vatiable1 ; 
        }
        else{
            result.innerHTML = "Variable is Undefined"
        }

    } 
</script>  

[출처] https://www.delftstack.com/ko/howto/javascript/javascript-check-if-variable-exists/

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
27 [wordpress, 워드프레스] 워드프레스로 쉽게 랜딩 페이지 만들기 (feat. 엘리멘터, GeneratePress, Divi) file 졸리운_곰 2024.12.20 545
26 [wordpress, 워드프레스] WordPress 페이지또는 글에 별도 CSS와 JavaScript 추가하기 file 졸리운_곰 2024.12.19 354
25 [wordpress 플러그인] 코스모스팜. 회원관리 1.메뉴에 로그인 넣기 file 졸리운_곰 2024.08.25 513
24 [wordpress 플러그인] WP-Members로 회원제 사이트 만들기 file 졸리운_곰 2024.08.25 749
23 [php worldpress] 워드프레스 새 서버 이전시 페이지 안나오는 문제 : How to Rewrite URLs with mod_rewrite for Apache on Ubuntu 20.04 file 졸리운_곰 2024.08.07 774
22 [php worldpress] PHP query to SQL server database (wordpress) 졸리운_곰 2024.07.28 503
21 [php worldpress] [위 에]wordpress 사용자 암호 화 원리 및 알고리즘 분석 졸리운_곰 2022.04.11 377
20 [wordpress] WPForms 워드프레스 폼빌더 사용법 file 졸리운_곰 2021.04.25 1715
19 [wordpress][워드프레스] 워드프레스에서 wpdb를 사용한 CRUD 작업 예 졸리운_곰 2021.04.15 356
18 워드프레스에서 wpdb를 사용한 CRUD 작업 예 졸리운_곰 2021.01.12 459
17 워드프레스 – CRUD file 졸리운_곰 2021.01.02 501
16 워드프레스 데이터베이스 들여다보기. file 졸리운_곰 2020.08.04 673
15 워드프레스 플러그인과 테마 비교 - 사이트별 플러그인 만들기 졸리운_곰 2020.04.21 501
14 워드프레스에서 js 스크립트 파일과 스타일시트를 올바르게 로드하는 방법 졸리운_곰 2020.04.21 735
13 워드프레스 플러그인 만들기 file 졸리운_곰 2020.04.21 500
12 워드프레스 숏코드: 완벽 가이드 file 졸리운_곰 2020.04.21 513
11 워드프레스 페이지 분석 file 졸리운_곰 2019.11.19 515
10 내가 본 워드프레스 핵심 구조 및 기능 (Wordpress Architecture and Function) file 졸리운_곰 2019.11.19 452
9 Embedding three.js in WordPress 워드프레스에서 three.js 사용 졸리운_곰 2019.11.08 517
8 How to Super Charge your WordPress with Microservices 워드프레스 마이크로서비스 file 졸리운_곰 2019.11.03 373
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED