함수는 코드의 집합니다. 함수의 자료형은 function
이며,
익명 함수, 선언적 함수가 있다. 함수에 관련된 예제를 몇가지 풀면서 함수와 더 친해지게 되었다.
function multiply(a,b) {
let output = 1;
for(let i = a; i <=b; i++) {
output *= i
}
return output
}
console.log(multiplyAll(1, 2))//2
console.log(multiplyAll(1, 3))//6
const max = function (array) {
let output = array[0];
for (arr in array) {
if (output < array[arr]) {
output = array[arr];
}
}
return output;
};
console.log(max([1, 2, 3, 4]));//4
const max = function (...array) {
let output = array[0];
for(const arr of array) {
if(output < arr) {
output = arr
}
}
return output;
};
console.log(max(1, 2, 3, 4));
const max = function(first, ...rests) {
let output
let items
//매개변수의 자료형에 따라 조건 분기하기
if(Array.isArray(first)) {
output = first[0]
items = first
} else if(typeof(first) === 'number') {
output = first
items = rests
}
//최대값 구하는 공식
for(const item of items) {
if(output < item) {
output = item
}
}
return output
}
console.log(`max(배열): ${max([1,2,3,4])}`) //4
console.log(`max(배열): ${max(1,2,3,4)}`) //4