JavaScript_1_자료형

🙋🏻‍♀️·2022년 4월 6일
0

[자료형]



✔️숫자형

🔹거듭제곱

 console.log(2 ** 3) //2*2*2를 출력하라는 뜻. 2의 세제곱



✔️문자열 활용

🔹문자열

console.log("He said \"I'm Iron man\"");
console.log('He said "I\'m Iron man"');
console.log("He said \"I'\m Iron man\"")
console.log('He said \"I\'m Iron man\"')
(헷갈리면 내부에 있는 따옴표들 앞에 다 역슬래시 쓰면 됨)

//He said "I'm Iron man"
He said "I'm Iron man"
He said "I'm Iron man"
He said "I'm Iron man"
(모두 똑같은 문장 출력됨)



이렇게 매번 하기 번거로우니까
백틱(`) 사용하면 편리함

console.log(He said "I'm Iron man")





✔️불리언

🔹불리언의 연산 AND OR NOT

불리언의 연산을 하기 위해선 명제를 확실히 알아야 함.

명제 : 참과 거짓이 확실한 문장


  1. AND 연산 (&&)
    : x와 y가 모두 참일때만 x AND y가 참

  1. OR연산 (||)
    : x와 y중 하나라도 참이면 x OR y는 참

  1. NOT 연산 (!)
    : 반대로 뒤집어 주는 역할.
    참이면 거짓으로, 거짓이면 참으로
    ex)console.log(!true)-->false
    ex)console.log(!!true)-->true(트루의 반대의 반대)





✔️불린형

console.log(2 > 1); --> true
console.log(2 < 1); --> false
console.log(3 >= 2); --> true
console.log(3 <= 3); --> true
console.log(3 === 3); --> true
console.log(3 !== 3); --> false





✔️typeof 연산자

typeof 연산자 : 해당하는 자료형을 문자열로 되돌려줌

◾괄호를 사용해서 연산자의 우선순위를 높여줘야 함
(사칙연산보다 typeof연산자의 우선순위가 높아서 출력 이상하게 됨)

 console.log(typeof ('Hello' + 'Codeit'));
 console.log(typeof (8 - 3));

// string
number 출력

📢예시1

let name = 'Codeit'
function sayHello(){
  console.log('Hello')
}
console.log(typeof name); 
console.log(typeof sayHello);

//string 
function 출력





✔️형변환

▪️ 자바스크립트에서 문자열로 바꾸고 싶을땐 string
▪️ 숫자로 바꾸고 싶을땐 Number
▪️ 불린으로 바꾸고 싶으면 Boolean

console.log(Number('10')+Number('5'));
console.log(String(10)+String(5));

//15
문자열 105 출력

❗문자->숫자, 숫자->문자로 형변환 가능
주의해야할 점은 숫자가 아닌 형태의 문자 값들은 숫자로 변환할 때 NaN값이 됨. 숫자가 아니라는 뜻


❗불린형에서 false인 경우 : ' '(빈 문자열),숫자의 경우 0,NaN





✔️형변환2




❗ 더하기 연산자는 문자열끼리 더하는 기능도 있기 때문에 주의하기


🔹산술연산자

❗❗❗❗
console.log(4 + '2'); : 문자열 42(한쪽이라도 문자열있으면 문자열로 변환)

console.log(4 + 2); : 숫자 6
console.log(4 - true); :3
console.log(4 * false); :0
console.log(4 / '2'); : 문자열 2가 숫자 2로 변환됨
console.log('4' ** true); : 4
console.log(4 % 'two'); : 'two'라는 문자열은 숫자형으로 바꾸면 NaN값.
 NaN은 어떤값과 연산해도 NaN





✔️관계 비교 연산(<, <=, >, >=)


▪️ 등호 세개면 일치, 등호 2개면 동등


◾일치, 불일치(!==)
console.log(1 === '1'); //일치비교는 형변환이 일어나지 않음
console.log(1 === true);
//둘 다 false

◾동등,부등(!=)
console.log(1 == '1')//동등비교는 숫자 형태로 형변환이 일어남
console.log(1 == true);
//둘 다 true





✔️템플릿 문자열(template String)


let myNumber = 3;

function getTwice(x){
return x * 2;
}

console.log(${myNumber}의 두 배는 ${getTwice(myNumber)}입니다.);
//3의 두 배는 6입니다.





✔️자료형 null과 undefined

(null-의도적인 없음/undefined-처음부터 없음)

let codeit;
console.log(codeit);

//undefined 출력(기본적으로 자바스크립트에서는 값이 주어지지 않은 변수엔 언디파인드.
선언을 한 다음 값을 정해주지 않았다는 뜻)


console.log(null==undefined);-->동등 비교일땐 비슷한 의미여서 true 출력
console.log(null===undefined);-->일치 비교하면 두 값이 서로 다른 자료형이어서 false 출력


📢컵에 물을 담아 마시는 걸로 이해를해보자(null이해하기)

let cup;

console.log(cup);//빈 컵(변수선언)을 준비
cup='물';
console.log(cup);//컵에 물이 들어가야하니까 컵이라는 변수에 물을 넣음
cup=null;
console.log(cup);//물을 다 마셔서 없으니까(의도적으로 비움) null

//undefined
물
null





0개의 댓글