[JS] 변수와 자료형

minkyeongJ·2022년 4월 28일
0

코드라이언FE

목록 보기
20/23

1. 변수

1.1 변수의 형태

변수의 형태
var 변수명 = 데이터;
let 변수명 = 데이터;
const 변수명 = 데이터;

var 나변수 = 10; 을 하면

메모리 어딘가에 10이라는 수를 저장하고 나변수가 그 공간을 가리킨다.

1.2 변수명을 정할 때

  • 변수이름은 $, _ 를 제외한 공백, 특수문자, 구두점(글의 여러 가지 경계를 구분하기 위해 사용되는 반점(,), 온점(.), 물음표(?) 등등…)을 사용할 수 없습니다.
  • 첫 글자는 숫자가 될 수 없습니다.
  • 대소문자를 구별합니다.
  • 예약어가 쓰일 수 없습니다.
  • 유니코드 문자도 사용할 수 있습니다.
  • var, let, const의 키워드를 사용할 수 있습니다. 보통은 let을 사용하지만, 정확한 scope를 배우기 전에는 var를 사용하도록 하겠습니다.

ಢ_ಢ 이런 형태의 이모티콘도 변수명으로 사용할 수 있다.

ಢ_ಢ 글 정보

유니코드 이모티콘의 경우네는 변수명으로 옳지 않는 문자들이 들어가서 사용할 수 없어보인다.
☺ 유니 코드 번호: U+263A
☺ HTML코드: ☺

2. 변수의 자료형

var 변수하나 = 20;
var 변수둘 = 10;
var 변수셋 = 2;

document.write('변수하나 : ', 변수하나);
document.write('<br>');
document.write('변수둘 : ', 변수둘);
document.write('<br>');
document.write('변수셋 : ', 변수셋);
document.write('<br>');
document.write('변수하나+변수둘 : ', 변수하나+변수둘);
document.write('<br>');
document.write('변수하나-변수둘 : ', 변수하나-변수둘);
document.write('<br>');
document.write('변수하나/변수둘 : ', 변수하나/변수둘);
document.write('<br>');
document.write('변수하나*변수둘 : ', 변수하나*변수둘);
document.write('<br>');
document.write('변수하나**변수셋 : ', 변수하나**변수셋);
document.write('<br>');
document.write('변수하나%변수셋 : ', 변수하나%변수셋);

결과

2.1 원시자료형과 객체자료형

typeof 'hello world'   // String
typeof 100             // Number
typeof NaN             // Number
typeof true            // Boolean
typeof undefined       // undefined
typeof Symbol()        // Symbol
typeof null            // Object, 여기서부터 js가 어려워 집니다.
typeof []              // Object, 여기서부터 js가 어려워 집니다. 왜 Array가 아닐까요?
typeof {}              // Object
typeof function () {}  // function
typeof /정규표현식/gi   // Object

// Object.prototype.toString.call(데이터).slice(8, -1);
// 로 확실하게 알 수 있습니다.

여기서 String, Number, Boolean, undefind, Symbol, None은 원시자료형이다.
원시자료형을 제외한 나머지가 객체 자료형이다.

null의 분류가 Object인 이유는 개발자가 실수로 null일 때 예외문을 적어주지 않아서 발생한 이슈이다.

데이터 타입을 구분하는 이유

일반적인 프로그래밍 언어는 자바스크립트처럼 값으로 데이터 타입을 구분하지 않고, 변수 키워드를 통해 구분한다. 대표적으로 int, float, str 등이 그렇다. 하지만 자바스크립트는 데이터 타입과 상관 없이 var, let, const 세 개의 변수 키워드로 모든 데이터 타입을 정의할 수 있다. 그렇다고 해서 데이터 타입의 구분도 필요 없는 것은 아닌데, 자바스크립트 엔진은 저장된 값에 따라 데이터 타입을 나눈다.

var num = 1; // Number
var num = '1'; // String

이처럼 데이터 타입을 구분하는 가장 큰 이유는 메모리 공간 확보에 있다. 값은 2진수로 메모리에 저장되며 변수는 해당 메모리 공간의 주소값을 가리키게 되는데, 이때 필요한 최소 메모리 공간이 데이터 타입에 따라 다르다. 이외에도 데이터 타입이 필요한 이유에는 몇 가지가 더 있는데 크게 세 가지의 이유를 들자면 아래와 같다.

  • 값을 저장할 때 확보해야 하는 메모리 공간의 크기를 결정하기 위해
  • 값을 참조할 때 한번에 읽어 들여야 할 메모리 공간의 크기를 결정하기 위해
  • 메모리에 읽어 들인 2진수를 어떻게 해석해야 할지 결정하기 위해

2.2 리터럴 표현

const a = 1;

여기서 a는 상수이고, 1은 리터럴이다.

리터럴 표기법이란?

리터럴표기법이란, 변수를 선언함과 동시에 그 값을 지정해주는 표기법을 말한다.

//리터럴 표기법
var no = 3;
var obj = { name: 'JY', age: 20 }; // 객체리터럴 방식으로 만든 객체

정리

  • 상수는 메모리 위치(공간)이며, 메모리 값을 변경할 수 없다.
  • 리터럴은 메모리 위치(공간) 안에 저장되는 값이다.

3. 여러가지 내용들

3.1 (객체).constructor

  • (객체)의 생성자가 무엇인지 알려준다.
    주의! type을 알아내는 것과 생성자를 알아내는 것은 다르다.

3.2 부동소수점

소숫점 계산에 약하기 때문에 0.1 + 0.2 == 0.3 일 때 false가 나온다.
왜냐면 저 합의 결과 값은 0.30000004이기 때문이다.

3.3 JS는 9천조 까지 숫자를 사용가능하다.

BigInt를 사용하면 더 큰 수를 사용할 수 있다.

3.4 템플릿 리터럴

템플릿 리터럴은 내장된 표현식을 허용한다.

`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`

템플릿 리터럴은 이중 따옴표 나 작은 따옴표 대신 백틱(\` \`) (grave accent) 을 이용한다.
백틱 사이에 표현식을 넣을 수 있는데, 이는 $와 중괄호( $ {expression} ) 로 표기할 수 있다.
템플릿 리터럴 안에서 백틱 문자를 사용하려면 백틱 앞에 백슬러쉬()를 넣으면 된다.

`\`` === "`" // --> true

4. 메서드 종류

//문자열 (string)

let txt = 'ABCDEFGHIJKABC';
let txt_two = 'mom said \'hello world\'';

document.write(`txt : ${txt} <br>`);
document.write(`txt.length : ${txt.length} <br>`);
document.write(`txt[1] : ${txt[1]} <br>`);
document.write(`txt_two : ${txt_two} <br>`);

document.write(`txt.indexOf : ${txt.indexOf("F")} <br>`);
document.write(`txt.search : ${txt.search("FGH")} <br>`);
document.write(`txt.lastIndexOf : ${txt.lastIndexOf("Z")} <br>`);
document.write(`txt.slice(0, 3) : ${txt.slice(0, 3)} <br>`);
document.write(`txt.substring(0, 3) : ${txt.substring(0, 3)} <br>`);
document.write(`txt.substr(2, 5) : ${txt.substr(2, 5)} <br>`);

//정규표현식에서 한 번 더 다뤄드립니다.
document.write(`txt.replace('ABC', 'hojun') : ${txt.replace(/ABC/g, 'hojun')} <br>`);

document.write(`txt.toUpperCase() : ${txt.toUpperCase()} <br>`);
document.write(`txt.toLowerCase() : ${txt.toLowerCase()} <br>`);
// 문자열의 내장 함수
let txt = 'ABCDEFGHIJKABC';

document.write(txt.includes('ABC'), '<br>');
document.write(txt.startsWith('BCD'), '<br>');
document.write(txt.endsWith('AB'), '<br>');

document.write(txt.indexOf('AB', 3), '<br>');
//논리형 (boolean)
var logic1 = true;
var logic2 = false;
var logic3 = 30 > 20;
var logic4 = 30 < 20;

document.write(logic1, '<br>');  //true
document.write(logic2, '<br>');  //false
document.write(logic3, '<br>');  // true
document.write(logic4, '<br>');  // false
//null
var a = ''; 
var b = null;

document.write(a, '<br>');  // 
document.write(b, '<br>');  // null

//undefined
var c;
document.write(c, '<br>')  // undefined
//객체 (object)

// 함수는 후에 자세히 다룹니다.
function sum(x, y){
  return x + y;
}

let person = {
  //key: value
  name: '이호준',
  age: 10,
  height : 30,
  weight : 40,
  이력 : {'첫번째직장' : '하나', '두번째직장' : '둘'},
  기능 : sum
}
person.소속 = '바울랩';

document.write(`제 이름은 ${person.name} 입니다. <br>`);
document.write(`제 나이는 ${person.age} 입니다. <br>`);
document.write(`제 키는 ${person.height} 입니다. <br>`);

document.write(`제 이름은 ${person['name']} 입니다. <br>`);
document.write(`제 나이는 ${person['age']} 입니다. <br>`);
document.write(`제 키는 ${person['height']} 입니다. <br>`);

document.write(`제 소속는 ${person['소속']} 입니다. <br>`);
document.write(`제 이력은 ${person['이력']['첫번째직장']} 입니다. <br>`);
document.write(`제 기능은 ${person['기능'](10, 20)} 입니다. <br>`);
//배열 (array)

// 배열을 선언하는 다양한 방법
// let 과일 = ['사과', '수박', '복숭아', '딸기', '바나나'];
// let 과일 = new Array(5);
let 과일 = new Array('사과', '수박', '복숭아', '딸기', '바나나');

document.write(`${과일} <br>`);
document.write(`${과일[0]} <br>`);
document.write(`${과일[2]} <br>`);
//배열 내장함수

let 과일 = ['사과', '수박', '복숭아', '딸기', '바나나'];
let 과일선물 = ['체리', '멜론'];

document.write(`과일 : ${과일} <br>`);
let 꺼낸과일 = 과일.pop()
document.write(`과일.pop() : ${꺼낸과일} <br>`);
document.write(`과일 : ${과일} <br>`);
document.write(`과일.push() : ${과일.push(꺼낸과일)} <br>`);
document.write(`과일 : ${과일} <br>`);

document.write(`------------------ <br>`);

let 문자열 = 과일.toString()
document.write(`과일.toString()[1] : ${문자열[1]} <br>`);
document.write(`과일.join('!!*') : ${과일.join('!!*')} <br>`);
document.write(`과일.shift() : ${과일.shift()} <br>`);
document.write(`과일.unshift() : ${과일.unshift('호준')} <br>`);
document.write(`과일 : ${과일} <br>`);
document.write(`과일.splice(1, 0, '한라봉') : ${과일.splice(1, 0, '한라봉')} <br>`);
document.write(`과일 : ${과일} <br>`);
document.write(`과일.slice(1, 3) : ${과일.slice(1, 3)} <br>`);
document.write(`과일 : ${과일} <br>`);
document.write(`과일.concat(과일선물) : ${과일.concat(과일선물)} <br>`);
document.write(`과일 : ${과일} <br>`);
document.write(`과일.sort() : ${과일.sort()} <br>`);
document.write(`과일 : ${과일} <br>`);
document.write(`과일.reverse() : ${과일.reverse()} <br>`);
document.write(`과일 : ${과일} <br>`);
document.write(`['1', '11', '2', '22'].sort() : ${['1', '11', '2', '22'].sort()} <br>`);
document.write(`['1', '11', '2', '22'].length : ${['1', '11', '2', '22'].length} <br>`);
function compare(a, b) {
  if (a > b) {
    return -1;
  }
  if (a < b) {
    return 1;
  }
  return 0;
}

let 배열 = [1, 30, 4, 21, 100000]

배열.sort()
[1, 100000, 21, 30, 4]

배열.sort(compare)
[100000, 30, 21, 4, 1]

function compare(a, b) {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  return 0;
}

배열.sort(compare)
[1, 4, 21, 30, 100000]
배열.length
배열.map
배열.fillter
배열.find

배열
(5) [1, 4, 21, 30, 100000]

배열.map(x => x**2)
[1, 16, 441, 900, 10000000000]

과일.map(x => x[0])
(6) ['딸', '바', '복', '수', '하나', '한']

let 전국구과일상점 = [['제주', 5], ['부산', 5], ['서울', 15], ['대전', 10]]

let 과일 = []
for (let x of 전국구과일상점){
    과일.push(x[1]);
}

과일
(4) [5, 5, 15, 10]

let 전국구과일상점 = [['제주', 5], ['부산', 5], ['서울', 15], ['대전', 10]];
전국구과일상점.map(x => x[1])
(4) [5, 5, 15, 10]

전국구과일상점.filter(x => x >= 10)
[]
전국구과일상점.filter(x => x[1] >= 10)
(2) [Array(2), Array(2)]

전국구과일상점.find(x => x[1] >= 10)
(2) ['서울', 15]

array
(5) [1, 30, 4, 21, 100000]
array.forEach(x => x**2)

let 제곱수 = []
array.forEach(x => 제곱수.push(x**2))

제곱수
(5) [1, 900, 16, 441, 10000000000]

//공백은 어디까지 병합되는가?
let fruits = 
[
  "사과",
  "오렌지",
  "자두",
];
fruits
(3) ['사과', '오렌지', '자두']

let fruits = 
[
  "사과",
  "오렌지",
  "자두",
];

let fruits = 
[
  "사
과",
  "오렌지",
  "자두",
];
VM3137:3 Uncaught SyntaxError: Invalid or unexpected token

let fruits = 
[
  "사과",

  "오렌지",
  "자두",
];
fruits
(3) ['사과', '오렌지', '자두']

let fruits = 
[
  `<ul>
    <li>abc</li>
   </ul>`,
  "오렌지",
  "자두",
];
fruits 
(3) ['<ul>\n    <li>abc</li>\n   </ul>', '오렌지', '자두']

// 값을 아규먼트로 전달할 때 주의!
function 값수정(x){
    x[1] = 100;
}
값수정(fruits)
fruits
(3) ['<ul>\n    <li>abc</li>\n   </ul>', 100, '자두']
function 값수정2(x){
    x = 100;
}
let xx = 1000;
값수정2(xx)
xx
1000
a = [1, 2, 3, 4, 5]
(5) [1, 2, 3, 4, 5]
b = a
(5) [1, 2, 3, 4, 5]
값수정(b)
undefined
a
(5) [1, 100, 3, 4, 5]
b
(5) [1, 100, 3, 4, 5]

// 한 단계 깊은 복사
a = [1, 2, 3, 4, 5]
b = [...a] 
(5) [1, 2, 3, 4, 5]

값수정(b)

a
(5) [1, 2, 3, 4, 5]
b
(5) [1, 100, 3, 4, 5]

[...a, ...a, 1000, ...a]
(16) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1000, 1, 2, 3, 4, 5]

a = [1, 2, 3, 4, 5]

b = a.slice()
(5) [1, 2, 3, 4, 5]

b
(5) [1, 2, 3, 4, 5]

b[1] = 1000
b
(5) [1, 1000, 3, 4, 5]

// length
fruits.length;
124
fruits
(124) [비어 있음 × 123, '사과']
let fruits = [];
fruits.length = 10;
10
fruits
(10) [비어 있음 × 10]
fruits[3] = undefined
undefined
fruits 
(10) [비어 있음 × 3, undefined, 비어 있음 × 6]
fruits[4] = null
null
fruits
(10) [비어 있음 × 3, undefined, null, 비어 있음 × 5]
let arr = new Array("사과", "배", "기타");
// 다차원 배열

let 전교점수 = [
           // 1반
           [[10, 20, 30, 40, {name:'leehojun', age:10}],
           [20, 30, 40, 50, 60]],
           // 2반
           [[10, 20, 30, 40, 50],
           [20, 30, 40, 50, 60]],
         ];

// document.write(전교점수[0][1][4]['age']);

// matrix
let m = [[1, 2, 3],
         [1, 2, 3],
         [1, 2, 3]]

document.write(m + m);

참고자료

데이터 타입을 나누는 이유
리터럴
템플릿 리터럴

profile
멋진 프론트엔드 개발자를 위하여!

0개의 댓글