01. 함수의 기본 형태
- 익명 함수란 이름이 없는 함수로
function () {}
형태로 만듭니다.
- 선언적 함수란 이름이 있는 함수로
function 함수 이름 () {}
형태로 만듭니다.
- 함수의 괄호 안에 넣는 변수를 매개 변수라고 합니다. 매개 변수를 통해 함수는 외부의 정보를 입력받을 수 있습니다.
- 함수의 최종적인 결과를 리턴 값이라고 합니다. 함수 내부에
return
키워드를 입력하고 뒤에 값을 넣어서 생성합니다.
- 가변 매개변수 함수란 매개 변수의 개수가 고정되어 있지 않은 함수를 의미합니다. 나머지 매개 변수 (…)를 활용해서 만듭니다.
- 전개 연산자란 배열을 함수의 매개 변수로써 전개하고 싶을 때 사용합니다.
- 기본 매개 변수란 매개 변수 기본값이 들어가게 하고 싶을 때 사용하는 매개 변수입니다.
확인 문제
1. A부터 B까지 범위를 지정했을 때 범위 안의 숫자를 모두 곱하는 함수를 만들어 보세요.
<script>
console.log(multiplyAll(1, 2))
console.log(multiplyAll(1, 3))
</script>
2. 다음 과정에 따라 최대값을 찾는 max()
함수를 만들어 보세요.
2-1. 매개 변수로 max([1,2,3,4])
와 같은 배열을 받는 max()
함수를 만들어보세요.
<script>
const max = {
let output = array[0]
}
console.log(max([1,2,3,4]))
</script>
2-2. 매개 변수로 max(1, 2, 3, 4)와 같이 숫자를 받는 max()
함수를 만들어 보세요.
<script>
const max = {
let output = array[0]
}
console.log(max(1,2,3,4))
</script>
2-3. max([1,2,3,4])
와 max(1, 2, 3, 4)
형태를 모두 입력할 수 있는 max()
함수를 만들어보세요.
<script>
const max = {
let output
let items
}
console.log(`max(배열): ${max([1,2,3,4])}`)
console.log(`max(숫자): ${max(1,2,3,4)}`)
</script>
코멘트
1. A부터 B까지 범위를 지정했을 때 범위 안의 숫자를 모두 곱하는 함수
<script>
//a -> b 범위 내의 숫자를 모두 곱함.
function multiplyAll (a, b) {
let result = 1
for (let i = a; i <= b; i++) {
result = result * i
}
return result
}
console.log(multiplyAll(1, 2))
console.log(multiplyAll(1, 3))
</script>
2-1. 매개 변수로 max([1,2,3,4])
와 같은 배열을 받는 max()
함수
<script>
// 배열을 매개변수로 받으려면 함수의 매개변수를 다음과 같이 작성하면 된다.
const max = function (array) {
let output = array[0];
// 반복문을 이용해서 기존 값과 현재 값을 비교한 후 현재 값이 더 크면 기존 값에 덮어 씌운다.
for (i in array) {
if (output < array[i]) {
output = array[i];
}
}
return output;
};
console.log(max([1, 2, 3, 4]));
</script>
2-2. 매개 변수로 max(1, 2, 3, 4)와 같이 숫자를 받는 max()
함수
<script>
const max = function (...array) {
let output = array[0];
for (i in array) {
if (output < array[i]) {
output = array[i];
}
}
return output;
};
console.log(max(1, 2, 3, 4));
</script>
2-3. max([1,2,3,4])
와 max(1, 2, 3, 4)
형태를 모두 입력할 수 있는 max()
함수
<script>
const max = function (array1, ...array2) {
let output;
let items;
if (Array.isArray(array1)) {
output = array1[0];
items = array1;
} else if (typeof array1 === "number") {
output = array1;
items = array2;
}
for (i of items) {
if (output < i) {
output = i;
}
}
return output;
};
console.log(`max(배열): ${max([1, 2, 3, 4])}`);
console.log(`max(숫자): ${max(1, 2, 3, 4)}`);
</script>
02. 함수 고급
- 콜백 함수란 매개 변수로 전달하는 함수를 의미합니다.
- 화살표 함수란 익명 함수를 간단하게 사용하기 위한 목적으로 만들어진 함수 생성 문법입니다.
()=>{}
형태로 함수를 만들고, 리턴값만 가지는 함수라면 ()=> 값
형태로 사용할 수 있습니다.
- 즉시 호출 함수란 변수의 이름 충돌을 막기 위해 코드를 안전하게 사용하는 방법입니다.
- 자바스크립트의 문법 오류를 더 발생시키는 엄격 모드는 실수를 줄일 수 있는 방법입니다. ‘use strict’라는 문자열을 블록 가장 위쪽에 배치해서 사용할 수 있습니다.
확인 문제
1. filter 함수의 콜백 함수 부분을 채워서 (1) 홀수만 추출, (2) 100이하의 수만 추출, (3) 5로 나눈 나머지가 0인 수만 추출해 주세요. 그리고 코드의 실행 결과를 적어보세요.
<script>
// 변수를 선언합니다.
let numbers = [273,25,75,52,103,32,57,24,76]
// 처리합니다.
// 출력합니다.
console.log(numbers)
</script>
2. 이전에 반복문 부분에서 살펴보았던 다음과 같은 코드를 배열의 forEach 메소드를 사용하는 형태로 변경해 주세요.
<script>
const array = ['사과', '배', '귤', '바나나']
console.log('# for in 반복문')
for (const i in array) {
console.log(i)
}
console.log('# for of 반복문')
for (const i of array) {
console.log(i)
}
</script>
코멘트
1. 각각 실행 후 결과 첨부
1-1. 홀수만 추출
<script>
// 변수를 선언합니다.
let numbers = [273, 25, 75, 52, 103, 32, 57, 24, 76];
// 처리합니다.
numbers = numbers.filter((value) => value % 2 !== 0);
// 출력합니다.
console.log(numbers);
</script>
1-2. 100이하의 수만 추출
<script>
// 변수를 선언합니다.
let numbers = [273, 25, 75, 52, 103, 32, 57, 24, 76];
// 처리합니다.
numbers = numbers.filter((value) => value <= 100);
// 출력합니다.
console.log(numbers);
</script>
1-3. 5로 나눈 나머지가 0인 수만 추출
<script>
// 변수를 선언합니다.
let numbers = [273, 25, 75, 52, 103, 32, 57, 24, 76];
// 처리합니다.
numbers = numbers.filter((value) => value % 5 === 0);
// 출력합니다.
console.log(numbers);
</script>
2. forEach 메소드를 사용하여 출력.
<script>
console.log("# for in 반복문 -> forEach로 변환");
array.forEach((value, index) => console.log(index));
console.log("# for of 반복문-> forEach로 변환");
array.forEach((value) => console.log(value));
</script>
-- 출력 결과 --
# for in 반복문 -> forEach로 변환
0
1
2
3
# for of 반복문-> forEach로 변환
사과
배
귤
바나나