🗺️

2. 변수

Index

2. 변수

2.1 변수란?

 
변수는 ‘변할 수 있는 수’, ’변할 수 있는 정보’라는 뜻입니다.
프로그램을 만드는 데 필요한 숫자나 문자와 같은 데이터를 보관할 공간이 필요한데, 물건을 잠시 보관하는 상자 같은 역할을 하는 것이 변수입니다.
변수는 선언하고 할당하고 사용할 수 있습니다. 또한, 변수는 ‘변할 수 있는 수’이므로 지정된 값을 계속 바꿀 수 있습니다.
<!DOCTYPE html> <html> <head> <title>변수</title> </head> <body> <script> var 나변수 = 10; </script> </body> </html>
 
notion imagenotion image
 
변수명을 정할 때
  • 변수이름은 $, _ 를 제외한 공백, 특수문자, 구두점(글의 여러 가지 경계를 구분하기 위해 사용되는 반점(,), 온점(.), 물음표(?) 등등…)을 사용할 수 없습니다.
  • 첫 글자는 숫자가 될 수 없습니다.
  • 대소문자를 구별합니다.
  • 예약어가 쓰일 수 없습니다.
  • 유니코드 문자도 사용할 수 있습니다.
  • var, let, const의 키워드를 사용할 수 있습니다. 보통은 let을 사용하지만, 정확한 scope를 배우기 위해서는 var를 사용하도록 하겠습니다.
var a; var my_name;
 
자바스크립트에서 변수를 선언할 때에는 앞에 var을 써줍니다. 변수의 타입과 var 외 다른 키워드는 뒤에서 더 자세하게 알아보도록 하겠습니다.
 
변수를 할당하는 방법은 다음과 같습니다.
 
a = 1; my_name ="lee";
 
console.log(a); console.log(my_name);
 
변수에 저장된 값을 프로그램을 통해서 확인할 수 있습니다. 구글 chrome을 통해서 콘솔창에 찍히는 값을 확인해 보도록 하겠습니다.
 

2.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('변수하나%변수셋 : ', 변수하나%변수셋);
 
notion imagenotion image
 
우리가 인터넷으로 물건을 주문하면 주문한 물건의 크기에 걸맞는 택배상자에 담겨서 오게 됩니다.
이와 같이 변수도 그 크기에 맞는 형식을 가지고 있습니다. 아래 간단하게 몇가지만 요약해 보았어요. 모든 자료형이 다 정리되어 있는 것은 아닙니다.
 
typeof 'hello world' // String typeof 100 // Number typeof NaN // Nnumber 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); // 로 확실하게 알 수 있습니다.
 
변수의 자료형은 다양한 데이터를 용도에 맞게 쓰기 위해서 입니다. 보통 언어에서는 변수의 자료형과 함께 변수를 선언하지만 자바스크립트는 자료형을 함께 쓸 필요는 없습니다.
 
//ES6 const 이름 = '이호준'; const 소속 = '제주코딩베이스캠프 운영진입니다.' let 주소 = '서울'; 주소 = '제주'; document.write(이름, '<br>'); document.write(소속, '<br>'); document.write(주소, '<br>'); document.write(소속[2], '<br>'); document.write(소속[3], '<br>');
 
notion imagenotion image
 
여기서 문자열 자료형에 대해 좀 더 알아보고 가도록 하겠습니다. 문자열은 작은따옴표('예시')큰따옴표("예시")로 둘러싼 것을 말합니다.
문자열은 순서가 있습니다. 순서가 있는 자료형을 시퀀스형 자료형이라고 합니다. 순서는 0부터 시작하며 띄어쓰기도 문자로 취급합니다. 이 순서를 index라고 부르며 위와 같이 index로 호출하는 것을 indexing이라고 합니다.
 
notion imagenotion image
 

2.3 자료형에 대해 조금 더 알아봅시다

 
변수의 자료형에 대하여 좀 더 폭넓게 알아보도록 하겠습니다. 여기서 몇가지 메서드를 사용하는데, 메서드 종류를 다 암기하실 필요는 없습니다. 자주 사용하시는 것은 자연스럽게 암기가 되실거에요!
 
//숫자형 (Number) var num = 10; document.write(num, '<br>'); // 10 document.write(num/3, '<br>'); // 3.3333.. document.write(parseInt(num/3), '<br>'); // 3 /* 숫자형의 사칙연산 */ document.write("더하기 : ", 2 + 2.5, '<br>'); // 4.5 document.write("빼기 : ", 5 - 7, '<br>'); // -2 document.write("곱하기 : ", 3 * 2, '<br>'); // 6 document.write("나누기 : ", 2/2, '<br>'); // 1 /*특수 숫자 값*/ document.write("무한대 : ", 1/0,'<br>'); // Infinity document.write( "숫자가 아님" / 2 ); // NaN, 문자열을 숫자로 나누면 오류가 발생합니다. // let number = 1e9; // let number = 123e-5; // let number = 1.23e9; // let number = 0b1010; //0, 1 -> 10 2진법 (바이너리, binary) // let number = 0o12; //0 ~ 7 -> 10 8진법 (옥타, octa) // let number = 0xff; //0 ~ f -> 255 16진법 (헥사, hexa) // let number = parseInt('13', 10) let number = parseFloat('13.3px.10') document.write(number, '<br>'); document.write(0.1 + 0.2 == 0.3, '<br>'); document.write(9999999999999999999, '<br>'); // Big.js, BigNumber.js, Decimal.js, Math.js 등으로 해결할 수 있습니다. 회사 컨벤션에 맞게 사용하시고, 저는 문자열로 처리 또는 9999999999999n + 3n으로 처리합니다.
// Number 관련 함수 let n = 10000; let nFloat = 10000.123123123; let s = '10,000,000'; document.write(`n : ${n} <br>`); document.write(`n.toLocaleString() : ${n.toLocaleString()} <br>`); document.write(`s : ${s} <br>`); document.write(`s.replace(/,/g, '') : ${s.replace(/,/g, '')} <br>`); document.write(`parseInt(s, 10) : ${parseInt(s, 10)} <br>`); document.write(`n.toFixed(10) : ${n.toFixed(10)} <br>`); document.write(`nFloat.toFixed(3) : ${nFloat.toFixed(3)} <br>`); document.write(`nFloat.toExponential(4) : ${nFloat.toExponential(4)} <br>`); document.write(`Number(true) : ${Number(true)} <br>`); document.write(`Number(false) : ${Number(false)} <br>`); document.write(`Number('') : ${Number('')} <br>`); document.write(`Number(' ') : ${Number(' ')} <br>`); document.write(`Number('hello') : ${Number('hello')} <br>`); document.write(`Number('10 20') : ${Number('10 20')} <br>`); document.write(`Number('10 ') : ${Number('10 ')} <br>`); document.write(`Number(' 10') : ${Number(' 10')} <br>`); document.write(`Number(' 10 ') : ${Number(' 10 ')} <br>`); document.write(`Math.PI : ${Math.PI} <br>`); document.write(`Math.round(4.7) : ${Math.round(4.7)} <br>`); document.write(`Math.pow(2, 8) : ${Math.pow(2, 8)} <br>`); document.write(`Math.sqrt(64) : ${Math.sqrt(64)} <br>`); document.write(`Math.abs(-5) : ${Math.abs(-5)} <br>`); document.write(`Math.random() : ${Math.random()*10} <br>`); document.write(`Math.max(10, 20, 30, 40, 50) : ${Math.max(10, 20, 30, 40, 50)} <br>`); document.write(`Math.min(10, 20, 30, 40, 50) : ${Math.min(10, 20, 30, 40, 50)} <br>`);
 
//문자열 (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);
 
//메모리 주소 확인 불가, python은 가능 a = 100000000 //100000000 b = 100000000 //100000000 Object.is(a, b) //true //ECMA Script2015 추가 //https://stackoverflow.com/questions/50530936/is-there-any-method-to-check-memory-address-of-javascript-variable Object.is(0, -0) //false