[FRONT-END]

오류 해결 : ReferenceError: user1 is not defined

지기음 2023. 3. 16. 00:42

BootStrap으로 로그인 창을 만들던 중 해당 오류를 확인하였다. 처음에는 오류 조차 확인하지 못했다.

왜냐하면 

이부분이 개발자도구에서 체크되어있지 않았기 때문이다. 다들 나와 같은 실수를 하지 않기를 바란다. 

다시 오류부분으로 가보면 

user1이 정의되지 않았다는 오류이다. 하지만 난 분명히 user1을 선언을 하고 초기화까지 진행하였다.

그럼 문제가 뭐였느냐?

우선 코드를 보여주겠다. 

function moveRegister(){
    console.log("간다");
    alert("회원가입 창으로 이동합니다.");
    // location.href="register.html";
    window.location.replace("register.html");
}

function register(){
    let id = document.getElementById("id").value;
    let password = document.getElementById("password").value;
    let age = document.getElementById("age").value;

    if(id==""||password==""||age==""){
        alert("제대로 입력해주세요");
        return;
    }else{
        const user1 = {
            id : id,
            password : password,
            age : age
        };
        
    }
    localStorage.setItem("user",JSON.stringify(user1));
        alert("등록완료");
        console.log(user1);
        window.location.replace("index.html");

    
}

분명 초기화가 되어있다. 하지만 간과한 점 하나! {}안에서 선언된 변수라는 점,,,,,, 정말 기초적인 실수를 하였다. 반성하는 의미로 포스팅을 했다. 다음에는 이런 실수를 안해야지! 

다음은 고친 코드이다. 

function moveRegister(){
    console.log("간다");
    alert("회원가입 창으로 이동합니다.");
    // location.href="register.html";
    window.location.replace("register.html");
}

function register(){
    let id = document.getElementById("id").value;
    let password = document.getElementById("password").value;
    let age = document.getElementById("age").value;

    if(id==""||password==""||age==""){
        alert("제대로 입력해주세요");
        return;
    }else{
        const user1 = {
            id : id,
            password : password,
            age : age
        };
        localStorage.setItem("user",JSON.stringify(user1));
        alert("등록완료");
        console.log(user1);
        window.location.replace("index.html");
    }

    
}