(JavaScript) null, 정의되지 않음, 유형 검사
JavaScript에서 null과 undefined는 변수에 값이 없음을 나타내는 두 가지 다른 값입니다.
typeof 연산자를 사용하여 변수의 데이터 유형을 확인할 수도 있습니다.
1. 제로 체크 방법 및 코드
let myVariable = null;
if (myVariable === null) {
console.log("myVariable is null");
} else {
console.log("myVariable is not null");
}
변수가 null인지 테스트하려면 등호 연산자(===)를 사용하여 변수가 null인지 테스트합니다.
2. 정의되지 않은 테스트 방법 및 코드
변수가 정의되지 않았는지 확인하려면 typeof 연산자를 사용하고 결과가 “정의되지 않음”인지 확인합니다.
let myVariable;
if (typeof myVariable === "undefined") {
console.log("myVariable is undefined");
} else {
console.log("myVariable is defined");
}
3. 테스트 방법 및 코드 입력
변수의 데이터 유형을 확인하려면 typeof 연산자를 사용하십시오.
여기 몇 가지 예가 있어요.
let myNumber = 123;
console.log(typeof myNumber); // "number"
let myString = "Hello, World!";
console.log(typeof myString); // "string"
let myBoolean = true;
console.log(typeof myBoolean); // "boolean"
let myArray = (1, 2, 3);
console.log(typeof myArray); // "object"
let myObject = { name: "John", age: 30 };
console.log(typeof myObject); // "object"
배열의 경우 typeof 연산자는 “객체”를 반환합니다.
이 경우 Array.isArray() 함수를 사용하여 배열인지 확인할 수 있습니다.
let myArray = (1, 2, 3);
if (Array.isArray(myArray)) {
console.log("myArray is an array");
} else {
console.log("myArray is not an array");
}