사용자 정의 함수(function)
- 하나의 특별한 목적의 작업을 수행하도록 설계된 독립적인 블록
- 필요할 때마다 호출하여 해당 작업을 반복해서 수행할 수 있음
- 코드를 재활용
1. 함수 선언식
function 함수명(매개변수1, 매개변수2 ..){
함수가 호출되었을 때 실행할 문장
...
return 값
}
함수명(값, 값2 ...)
2. 함수 표현식
const 변수명 = function(매개변수1, 매개변수2 ..){
함수가 호출되었을 때 실행할 문장
...
return 값
}
변수명(값1, 값2 ..) //1. 과 2. 에서 2. 함수표현식을 좀 더 추천함
디폴트 매개변수
- 매개변수의 값을 설정하는 것
- 매개변수의 값을 정하지 않으면 기본값을 변수에 저장
function 함수명(매개변수1=값1, 매개변수2=값2, ...){
함수가 호출되었을 때 실행할 문장
...
return 값
}
함수명()
함수명(값1, 값2, ...)
나머지 매개변수
생략 접두사(...)를 사용하여 특정 위치의 인수부터 마지막 인수까지 한 번에 지정할 수 있음
function 함수명(매개변수1, ...매개변수2){
함수가 호출되었을 때 실행할 문장
...
return값
}
함수명(값1, 값2, 값3, 값4, 값5)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>함수</title>
</head>
<body>
<h2>함수</h2>
<script>
function func1(){
console.log('func1() 호출!')
}
func1()
func1()
function func2(num){
console.log(`전달받은 매개변수의 값: ${num}`)
}
func2() // undefined
func2(10)
func2('apple')
func2(true) // javascript는 type이 정해져있지 않음으로 인해 error가 발생할 수 있음
function func3(start, end){
let sum = 0
for(let i=start; i<=end; i++){
sum += i;
}
console.log(`${start}부터 ${end}까지의 총합: ${sum}`)
}
func3(1, 100)
func3(10) //10부터 undefined까지의 총합: 0
function func4(){
return '🎂'
}
func4() // jupyternotebook 처럼 자동 프린터 기능이 없음
console.log(func4) // 함수의 메모리를 찍음. 함수의 모양을 그대로 보여줌. 함수의 소스가 찍혀서 케이크 하나만 찍진 않음
// ƒ func4(){
// return '🎂'
// }
console.log(func4()) // 🎂 하나만 찍힘
const presents = func4() // 변수에 담아서 함수의 소스를 리턴해서 출력
console.log(presents) // 🎂 하나만 찍힘
console.log('-------------')
// 디폴트 매개변수
function func5(num1=1, num2=1){
console.log(`num1의 값:${num1}, num2의 값:${num2}`)
console.log(`${num1} * ${num2} = ${num1*num2}`)
}
func5()
func5(10, 3)
console.log('-------------')
function func6(...x){
console.log(`x의 값: ${x}`)
console.log(`x의 타입: ${typeof(x)}`)
for(i in x){
console.log(`i의 값: ${i}, x[${i}]: ${x[i]}`)
}
}
func6(30, 40, 70)
console.log('-------------')
function func7(x1, ...x2){
console.log(`x1의 값: ${x1}`)
console.log(`x2의 타입: ${x2}`)
}
func7(30, 40, 70); // 세미콜론은 서로 다른 함수를 구분해주는 역할
// 보너스!!
(function func8(){
console.log(`함수를 만들고 바로 호출합니다.`)
})();
</script>
</body>
</html>
호이스팅(hoisting)
- 인터프리터가 변수의 함수의 메모리공간을 선언 전에 미리 할당하는 것
- var로 선언한 변수의 경우 호이스팅 시, undefined로 변수를 초기화
- let과 const로 선언한 변수의 경우, 호이스팅 시 변수를 초기화하지 않음
함수정의 인터프리팅 결과
func1() function func1(){
... 함수 호이스팅 ...
function func1(){ ---> }
...
} func1()
func2() let func2
let func2 = function(){ 변수 호이스팅 func2()
... ---> function func2(){
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>호이스팅</title>
</head>
<body>
<h2>호이스팅</h2>
<script>
func1();
func2();
function func1(){
alert('func1 호출!')
}
const func2 = function(){
alert('func2 호출!')
}
// cannot access 'func2' before initialization
</script>
</body>
</html>
화살표 함수
- function 키워드를 사용하여 함수를 만드는 것보다, 간단하게 표현
- 화살표 함수는 항상 익명
* 매개변수가 없을 경우
const 함수명 = () => {
함수가 호출되었을 때 실행될 문장
...
}
const 함수명 = () => 함수가 호출되었을 때 실행될 문장 # 한줄 표현식
* 매개변수가 있을 경우
const 함수명 = (매개변수1, 매개변수2, ...) => {
함수가 호출되었을 때 실행될 문장
...
}
const 함수명 = (매개변수1, 매개변수2, ...) => 함수가 호출되었을 때 실행될 문장
✔ 매개변수가 1개인 경우는 소괄호를 생략할 수 있음
const 함수명 = 매개변수1 => 함수가 호출되었을 때 실행될 문장
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>화살표 함수</title>
</head>
<body>
<h2>화살표 함수</h2>
<script>
const func1 = () => console.log('안녕하세요. JavaScript!')
func1();
console.log('-----------')
const func2 = (x, y) => console.log(`두 수의 합: ${x+y}`)
func2(10, 3)
console.log('-----------')
const func3 = x => x * x;
const result = func3(10);
console.log(`10의 제곱은: ${result}`); // 파이썬의 람다함수와 비슷함
console.log('-----------')
const func4 = (x, y) => {
let sum=0;
for(let i=x; i<=y; i++){
sum += i
}
return sum
}
const total = func4(1, 100)
console.log(`1부터 100까지의 합: ${total}`)
console.log('-----------')
let age = prompt('나이를 입력하세요')
const isAdult = (age > 19) ? () => console.log('성인입니다.')
: () => console.log('미성년입니다.') // : 앞이 True일때, 뒤에가 False일때 실행할 문장이다.
isAdult()
</script>
</body>
</html>
객체(Object)
하나의 주제를 가지고 관련있는 프로퍼티를 가지고 있는 집합
프로퍼티(property)
- 이름과 값으로 구성된 정렬되지 않은 집합(파이썬의 클래스 안에 저장된 self와 같음)
- 프로퍼티는 함수도 저장할 수 있음 -> 프로퍼티 메소드
객체를 생성하는 방법
1. 리터럴(고정된 값, 상수, 픽스된 것) 표기법
const 객체명 = {
프로퍼티명1: 값1,
프로퍼티명2: 값2,
...
프로퍼티명n: function(){
프로퍼티가 호출되면 실행할 문장
...
}
}
2. 생성자를 이용
- 객체를 만드는 함수
function 생성자명(매개변수1, 매개변수2, ...){
this.프로퍼티명1 = 값1,
this.프로퍼티명2 = 값2,
...
this.프로퍼티명n: function(){
프로퍼티가 호출되면 실행할 문장
...
}
}
const 객체명1 = new 생성자명(값1, 값2, ...)
const 객체명2 = new 생성자명(값1, 값2, ...)
...
const 객체명3 = new 생성자명(값1, 값2, ...)
- new 연산자를 사용하여 객체를 생성하고 초기화할 수 있음
- 객체를 생성할 때 사용하는 함수를 생성자라고 함
- 새롭게 생성되는 객체를 초기화하는 역할
- 같은 형태의 객체를 여러개 생성할 때 유리
3. 클래스를 이용
- ECMA script6에 추가된 객체 생성 방법
- 내부적으로 생성자를 이용한 객체 생성 방법과 동일하게 작동
const 클래스명 = class {
constructor(매개변수1, 매개변수2, ...){
this.프로퍼티명1 = 값1
this.프로퍼티명2 = 값2
...
}
메소드명(매개변수1, 매개변수2 ...){
메소드가 호출되면 실행할 문장
...
}
}
const 객체명1 = new 클래스명(값1, 값2, ...)
const 객체명2 = new 클래스명(값1, 값2, ...)
...
const 객체명n = new 클래스명(값1, 값2, ...)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>객체</title>
</head>
<body>
<h2>객체</h2>
<script>
// 리터럴 표기법
const dog = {
name: '루시',
age: 13,
color: 'white',
birthday: '20091010',
getBirthday: function(){
return this.birthday;
}
}
console.log(dog.name)
console.log(dog.age)
console.log(dog.color)
console.log(dog.birthday)
console.log(dog.getBirthday())
console.log('-----------')
console.log(dog['name'])
console.log(dog['age'])
console.log(dog['color'])
console.log(dog['birthday'])
console.log(dog['getBirthday']())
console.log('-----------')
for(let i in dog){
console.log(`i:${i}, dog[${i}]:${dog[i]}`)
}
console.log('-----------')
// 생성자를 이용한 객체
function Dog(name, color){
this.name = name
this.color = color
this.eat = function(){
return `${this.name}는 먹습니다.`
}
}
const Rucy = new Dog('루시', 'white')
console.log(Rucy.name)
console.log(Rucy.color)
console.log(Rucy.eat())
console.log('-----------')
const PPomi = new Dog('뽀미', 'white')
console.log(PPomi.name)
console.log(PPomi.color)
console.log(PPomi.eat()) // 같은 형식의 객체를 만들어서 하나의 생성자 포맷으로 다른게 출력할 수 있음. 굳이 두번 하지 않아도 됨.
console.log('-----------')
// 클래스를 이용한 객체생성
const User = class {
constructor(userid, name, age){
this.userid = userid
this.name = name
this.age = age
}
getUserid(){
return `아이디는 ${this.userid} 입니다.`
}
}
const apple = new User('apple', '김사과', 20)
console.log(apple.userid)
console.log(apple.name)
console.log(apple.age)
console.log(apple.getUserid())
</script>
</body>
</html>
상속
- 클래스 기반의 객체지향 언어와 다름
- 자바스크립트는 프로토타입 기반의 객체지향 언어
✔ 프로토타입(prototype)
- 모든 객체는 프로토타입이라는 객체를 가지고 있음
- 모든 객체는 프로토타입으로부터 프로퍼티와 프로퍼티 메소드를 상속받음
- 모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받으며 상속되는 정보를 제공하는 객체를 프로토타입이라고 함
const dog = new Dog(); // Dog.prototype, Object.prototype # 두 개의 프로토타입으로 Dog의 객체가 생성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>프로토타입</title>
</head>
<body>
<h2>프로토타입</h2>
<script>
function Dog(color, name, age){
this.color = color
this.name = name
this.age = age
}
const Rucy = new Dog('white', '루시', 13)
console.log(`이름: ${Rucy.name}`)
console.log(`색상: ${Rucy.color}`)
console.log(`나이: ${Rucy.age}`)
Rucy.family ='포메라니안'
Rucy.getFamily = function(){
return this.family;
}
console.log(`종: ${Rucy.family}`)
console.log(`getFamily: ${Rucy.getFamily()}`) // 에러남 코드 받기
const PPomi = new Dog('white', '뽀미', 6)
console.log(`이름: ${PPomi.name}`)
console.log(`색상: ${PPomi.color}`)
console.log(`나이: ${PPomi.age}`)
// console.log(`종: ${PPomi.family}`)
// console.log(`getFamily: ${PPomi.getFamily()}`)
console.log('-----')
Dog.prototype.birthday = '20091210'
Dog.prototype.run = function(){
return this.name + '는 달립니다.'
}
console.log(`생년월일: ${Rucy.birthday}`)
console.log(`run: ${Rucy.run()}`)
console.log(`생년월일: ${PPomi.birthday}`)
console.log(`run: ${PPomi.run()}`)
</script>
</body>
</html>
Math 객체
- 수학에서 자주 사용하는 상수와 함수들을 미리 구현한 자바스크립트 표준 내장객체. 비교할 수 없는 값이 포함되어 있어면 NaN을 반환
mim(): 가장 적은 수를 반환. 매개변수가 전달되지 않으면 Infinity를 반환
max(): 가장 큰 수를 반환. 매개변수가 전달되지 않으면 -Infinity를 반환
round(): 소수점 첫번째 자리에서 반올림하여 그 결과를 반환
floor(): 소수점을 버림
ceil(): 소수점을 올림
random():0보다 크거나 같고, 1보다 작은 무작위 소수를 반환
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math 객체</title>
</head>
<body>
<h2>Math 객체</h2>
<script>
console.log(Math.min()) // Infinity
console.log(Math.max()) // Infinity
console.log(Math.min(1, -10, 1000, 0, '-100')) // 자동 형변환 되어, -100이 나오고 최솟값으로 리턴됨
console.log(Math.min(1, -10, 1000, 0, '마이너스백')) // NaN이 나옴. 비교할 수 없는 데이터가 포함되어 있기 때문`
console.log(Math.max(1, -10, 1000, 0))
console.log(Math.round(10.49)) // 10
console.log(Math.round(10.5)) // 11
console.log(Math.round(-10.49)) // -10
console.log(Math.round(-10.51)) // -11
console.log(Math.floor(10.49)) // 10
console.log(Math.floor(10.5)) // 10
console.log(Math.floor(-10.49)) // -11
console.log(Math.floor(- 10.51)) // -11
console.log(Math.ceil(10.49)) // 11
console.log(Math.ceil(10.5)) // 11
console.log(Math.ceil(-10.49)) // -10
console.log(Math.ceil(-10.51)) // -10
const rm = Math.random()
console.log(rm) // 0.7970126326567015
// 1~10 까지의 무작위 정수를 추출.
const rm1 = Math.floor(Math.random()*10) + 1
console.log(rm1)
</script>
</body>
</html>
String 객체
const str1 = 'JavaScript'
const str2 = new String('JavaScript')
str1 == str2 // true
str1 === str2 // false(똑같은 string이지만 서로 다른 메모리와 리터럴 객체를 만드는 방식이 달라서)
length: 문자열의 길이를 반환하는 프러퍼티
indexOf(): 특정 문자나 문자열이 처음으로 등장하는 위치를 인덱스로 반환
charAt(): 특정 문자열에서 전달 받은 인덱스에 위치한 문자를 반환
includes(): 특정 문자열에서 전달 받은 문자열이 포함되어 있는지 여부를 반환
substring(): 전달 받은 시작 인덱스부터 종료 인덱스 바로 직전까지의 문자열을 추출
substr(): 전달 받은 시작 인덱스부터 '전달 받은 갯수'만큼 문자열을 추출
replace(): 원본 문자열의 일부를 전달 받은 문자열로 치환
split(): 구분자를 기준으로 나눈 후 나뉜 문자열을 하나의 배열에 저장
trim(): 문자열의 앞 뒤 공백을 제거
toUpperCase(): 문자열을 모두 대문자로 변환
toLowerCase(): 문자열을 모두 소문자로 변환
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>string객체</title>
</head>
<body>
<h2>string객체</h2>
<script>
const str1 = '안녕하세요. JavaScript!'
console.log(str1)
console.log(str1.length) // 17개의 글자
console.log(str1.indexOf('J')) // 7
console.log(str1.indexOf('Java')) // 7
console.log(str1.indexOf('java')) // -1(못 찾았을 경우)
console.log(str1.indexOf('a')) // 8
console.log(str1.lastIndexOf('a')) // 10
console.log(str1.charAt(7)) // J
console.log(str1.includes('Java')) // True
console.log(str1.includes('java')) // False
console.log(str1.substring(7)) // 7 ~ 끝까지 // JavaScript!
console.log(str1.substring(7,11)) // Java
console.log(str1.substr(7, 4)) // Java // 곧 프로그램에서 사라질 함수
console.log(str1.replace('안녕하세요', 'Hello')) // Hello. JavaScript!
const str2 = '김사과, 오렌지, 반하나, 이메론, 배애리, 채리'
const students = str2.split(',')
console.log(students) // ['김사과', ' 오렌지', ' 반하나', ' 이메론', ' 배애리', ' 채리']
for(let i in students){
console.log(i, students[i])
}
// *결과*
// 0 김사과
// 1 오렌지
// 2 반하나
// 3 이메론
// 4 배애리
// 5 채애리
const str3 = ' JavaScipt '
console.log(`😃${str3}😃`) // 😃 JavaScipt 😃
console.log(`😃${str3.trim()}😃`) // 😃JavaScipt😃
console.log(`😃${str3.trim().toUpperCase()}😃`) // 😃JAVASCIPT😃
console.log(`😃${str3.trim().toLowerCase().toLowerCase()}😃`) // 😃javascipt😃
//메소드체인을 연속해서 사용 최근 프로그래밍 스타일
</script>
</body>
</html>
Date 객체
날짜, 시간 등을 쉽게 처리할 수 있는 내장 객체
연도(year)
- 2자리로 연도를 표기: 1900년 ~ 1999년
- 4자리로 연도를 표기: 2000년 ~
월(month)
- 0 ~ 11, 0(1월), 11(12월)
Data 객체를 생성하는 방법
new Date(): 현재 날짜 시간을 저장한 객체가 생성
new Date('날짜 문자열'): 해당 특정 날짜와 시간을 저장한 객체가 생성
new Date('밀리초'): 1970년 1월 1일 0시 0분 0초를 기준으로 해당 밀리초만큼 지난 날짜와 시간을 저장한 객체가 생성
new Date(년, 월, 일, 시, 분,. 초, 밀리초): 해당 날짜와 시간을 저장한 객체가 생성
Web API 객체
BOM(Browser Object Model): 비표준
window 객체
웹 브라우저의 창이나 탭을 표현하기 위한 객체들이며 웹 브라우저는 window객체를 이용하여 브라우저 창을 표현할 수 있음
window.alert()
window.confirm()
window.prompt()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=+, initial-scale=1.0">
<title>Date 객체</title>
</head>
<body>
<h2>Date 객체</h2>
<script>
console.log(new Date()) // Thu Apr 06 2023 14:40:57 GMT+0900 (한국 표준시)
// 연도를 2자리로 사용하면 1900년
console.log(new Date(23, 4, 6)) // Sun May 06 1923 00:00:00 GMT+0900 (한국 표준시)
const current_time = new Date(2023, 3, 6, 14, 44, 00)
console.log(current_time)
console.log(`현재 연도: ${current_time.getFullYear}`)
console.log(`현재 월: ${current_time.getMonth()+1}`)
console.log(`현재 일: ${current_time.getDate()}`)
console.log(`현재 시간: ${current_time.getHours()}`)
console.log(`현재 분: ${current_time.getMinutes()}`)
console.log(`현재 초: ${current_time.getSeconds()}`)
</script>
</body>
</html>
setTimeout()
일정 시간이 지난 후 매개변수로 제공된 함수를 실행
const 함수명 = function(){
실행문
...
}
const st = setTimeout(함수명, 밀리초)
clearTimeout()
일정시간 후에 일어날 setTimeout()를 취소함
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setTimeout</title>
</head>
<body>
<h2>setTimeout</h2>
<script>
const hello = function(){
alert('안녕하세요. JavaScript')
}
const st = setTimeout(hello, 5000) // 5초 뒤에 alert창을 띄어줌
// clearTimeout(st) // 해당 setTimeout을 취소해줌
</script>
</body>
</html>
setInterval()
일정 시간마다 매개변수로 제공된 함수를 실행
clearInterval()
일정시간마다 일어날 setInterval()를 취소함
form 객체
- 일반적인 폼 요소에 접근할 때 사용
- document.forms 컬렉션을 이용해서도 접근할 수 있음
<form name='myform' id='regform' method='post' action='#'>
아이디: <input type="text" name="userid" id="id"><br>
비밀번호: <input type="password" name="userpw" id="pw"><br>
</form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setInterval</title>
</head>
<body>
<h2>setInterval</h2>
<script>
const hello = function(){
console.log('안녕하세요. JavaScript!')
}
const si = setInterval(hello, 3000) // 3초마다 연속해서 출력
const clearInter = function(){
clearInterval(si)
console.log('hello()가 중지되었음!')
}
</script>
<p><button onclick="clearInter()">중지</button></p>
</body>
</html>
폼 접근하기
const frm = document.myform // document는 body객체 안에 있는 문서, name으로 접근
const frm = docunent.forms['myform'] // name으로 접근
const frm = docunent.forms[0] // 한 문서의 여러개의 폼 중 첫번째 폼
const frm = document.getElementById('regform') // id로 찾는 방법
아이디 입력상자에 접근하기
const userid = frm.userid // name으로 접근
const userid = document.forms['myform'].elements[0] // 한 문서의 myform 폼 중 첫번째 요소
const userid = document.forms['myform'].elements['userid'] // name으로 찾음
const frm = docunent.forms[0][0] // 한 문서의 여러개 폼 중 첫번째 폼에 첫번째 요소로 접근
const frm = document.getElementById('id')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>폼 객체</title>
</head>
<body>
<h2>폼 객체</h2>
<form action="#" name="frm1">
<input type="text" name="userid" id="id" placeholder="아이디를 입력하세요"><br>
<input type="password" name="userpw" placeholder="비밀번호를 입력하세요">
</form>
<form action="#" name="frm2">
<input type="search" name="search" placeholder="검색어를 입력하세요">
</form>
<script>
const frm1 = document.frm1
console.log(frm1.userid.placeholder)
// frm2에 있는 search에 placeholder값을 출력
const frm2 = document.frm2
console.log(frm2.search.placeholder)
document.getElementById('id').value = 'apple'
document.forms['frm1'].elements['userpw'].value = '1004'
document.forms[1].elements[0].value = '코리아IT아카데미'
</script>
</body>
</html>
문제.
본인의 웹사이트에 적용
1. 가위바위보 게임(JavaScript 버전으로)
2. 로또번호(1~45) 예상 추출
3. 시계만들기
(시작)과 (종료) 버튼 추가하기