위로 아래

기본형

1. 기본형                      // 함수 정의문이 호출문보다 밑에 있어도 됨.
function 함수명 (){
    자바스크립트 코드;
}

2. 익명 함수                   // 함수 정의문이 호출문보다 밑에 있어도 됨.
참조 변수 = function(){
    자바스크립트 코드;
}

3. 재귀 함수                   // 반복문처럼 함수 안에서 자신(함수)를 또 불러옴.
function myFnc (){           // num = 10이 될 때까지 myFnc 함수를 반복 호출
    num++;
    if(num==10) return 0;
    function myFnc();
}

4. 즉시 실행 함수
(function () {
    자바스크립트 코드;
}());

5. 객체 만드는 함수 생성 방법 (함수 개별 생성)
function check (name, height){
    this.userName = name;
    this.userHeight = height;
    this.checkHeight = function(){
        if(this.userHeight>180) {document.write(this.userName + "키크네!<br>")}
        else {document.write(this.userName + "난쟁이!<br>")};
    } 
}
const gaesol = new check ("개솔이", 170);
const gaesolFriend = new check ("개솔이 친구", 190);

gaesol.checkHeight();
gaesolFriend.checkHeight();


6. 객체 만드는 함수 생성 방법 (함수 프로토타입 생성)
function check (name, height){
	this.userName = name;
	this.userHeight = height;
}

check.prototype.checkHeight = function(){
	if(this.userHeight > 180) {
		document.write(this.userName + " 키 크네! <br>");
	} else {
		document.write(this.userName + " 난쟁이! <br>");
	}
}
const gaesol = new check("개솔이", 170);
const gaesolFriend = new check("개솔이친구", 190);

gaesol.checkHeight();
gaesolFriend.checkHeight();


7. 콜백함수 ( 함수를 인자로 쓰는 함수 )
function callTenTimes (myFnc){  // 함수에 인자로 함수가 들어갔다.
	for(let i=0;i<10;i++){
		myFnc();   // 인자로 들어온 함수에 ()달아서 실행
	}
}

callTenTimes(function(){   // 함수 호출하면서, 인자에 함수 정의
	console.log("함수호출");
})

재귀함수 : 자기 자신을 호출하는 함수. 팩토리얼처럼 5!=5*4*3*2*1 -> 1씩 빼면서 자기 자신의 함수를 계속 호출하는 것.

 


내장 함수

parseInt("15.2px") -> 15    // 문자열 데이터를 정수형 데이터로 반환
parseFloat(65.5%) -> 65.5   // 문자열 데이터를 실수형 데이터로 반환
String(50) -> "50"          // 문자형 데이터로 반환
Number("50") -> 50          // 숫자형 데이터로 반환 (prompt로 입력받은 숫자는 처음에 다 문자다)
Boolean(5) -> true, Boolean(null) -> false  // 논리형 데이터로 반환
isNaN("5-3") -> true, isNaN("53") -> false  // 숫자가 아닌 문자가 있을 때만 true 반환
eval("15+5") -> 20          // 문자형 데이터를 따옴표 없는 자바스크립트 코드로 처리

 

 


Compare Function (함수의 인자로 들어가는 함수)

기본형
let num = [10, 3, 8, 4, 1];

1. 정석형
num.sort(function(a,b){return b-a});

2. 간단형 (화살표 함수 이용)
num.sort((a,b) => return b-a)

3. 긴 형
let comp = function(a,b){return b-a}
num.sort(comp);


sort 메소드

let arr = [5,3,4,1,2];
arr.sort(function (a, b) { return a - b });
console.log(arr);
// 결과: [1, 2, 3, 4, 5]
arr.sort(function (a, b) { return b - a });
console.log(arr);
// 결과: [5, 4, 3, 2, 1]

forEach 메소드
arr.forEach((item, index) => {
	console.log(index + '번째 요소는 '+item+'입니다.');
})

map 메소드

let output = arr.map((item,index) => {
	return item * item;  // 배열의 모든 요소를 제곱해서 새로운 배열을 생성
})
console.log(output);

filter 메소드

let output = arr.filter((item, index) =>{
	return item % 2 == 0;	//  짝수만 추출
})
console.log(output);