[HTML/CSS] Java Script 형 변환

stow·2023년 10월 12일

Java Script

목록 보기
3/14

형 변환 : 함수와 연산자에 전달되는 값은 대부분 적절한 자료형으로 자동 변환되는 것

암시적 형 변환

let result1 = 1 + '2';
console.log(result1);
console.log(typeof result1);

결과 = 12
	  string
      
let result2 = "1" + true;
console.log(result2);
console.log(typeof result2);
결과 = 1true
	  string
  • 문자열과 다른 데이터 타입이 더하기 연산자로 만나면 문자열이 우선시 된다.
let result3 = 1 - "2";
console.log(result3);
console.log(typeof result3);

let result4 = '2' * '3';
console.log(result4);
console.log(typeof result4);

let result5 = '6' / '2';
console.log(result5);
console.log(typeof result5);

결과 = -1
	   number
	   6
	   number
	   3
	   number
  • 더하기 연산자가 아닌 빼기, 곱하기, 나누기 등, 문자 + 문자가 왔을때도 숫자가 우선 순위가 된다.

명시적 형 변환
1-1 Boolean

console.log(Boolean(0));
console.log(Boolean(""));
console.log(Boolean(null));
console.log(Boolean(undefined));
console.log(Boolean(NaN));
console.log("------------");
console.log(Boolean("false"));
console.log(Boolean({}));

결과 = 
false
false
false
false
false
------------
true
true

console.log(Boolean("false")) : 결과값이 true가 나오는 이유는 문자열은 아무리 들어있는 값이 false라고 하더라도 영향을 미치지 않고 문자열이니 console.log(Boolean("")); 코드와 같이 빈 문자열이 아니라 어떤 값이 있는 문자열은 무조건 true가 나온다.

추가로 console.log(Boolean({})) 코드 같은 경우도 값이 비어 있다 할지라도 결과값은 true가 나온다.

1-2 문자열

let result6 = String(123);
console.log(typeof result6);
console.log(result6);

let result7 = String(true);
console.log(typeof result7);
console.log(result7);

let result8 = String(false);
console.log(typeof result8);
console.log(result8);

let result9 = String(null);
console.log(typeof result9);
console.log(result9);

let result10 = String(undefined);
console.log(typeof result10);
console.log(result10);

결과 값 = 
string
123
string
true
string
false
string
null
string
undefined

1-3 숫자형

let result11 = Number("123");
console.log(result11);
console.log(typeof result11);

결과 값 = 
123
Number
profile
맹구의 돌 수집품 중 하나

0개의 댓글