: 함수에 인수 안에, 함수가 들어가 있는 것
[Node.js 강좌] 10. Callback 함수란 무엇인가 ?
cmd 창에서, node
만 입력하면, 해당 화면처럼 나온다.
그리고 아래의 코드들을 하나씩 입력해보자.
> console.log(1+1);
2
undefined
> a = [3,1,2]; console.log(a);
[ 3, 1, 2 ]
undefined
> a = [3,1,2]; a.sort(); console.log(a);
[ 1, 2, 3 ]
undefined
> a = [3,1,2]; function b(v1, v2){return v2-v1}; a.sort(b); console.log(a);
[ 3, 2, 1 ]
undefined
> a = [3,1,2]; function b(v1, v2){return v1-v2}; a.sort(b); console.log(a);
[ 1, 2, 3 ]
undefined
> a = [3,1,2]; function b(v1, v2){return 0}; a.sort(b); console.log(a);
[ 3, 1, 2 ]
undefined
> a = [3,1,2]; function b(v1, v2){console.log('c',v1,v2); return 0;}; a.sort(b); console.log(a);
c 1 3
c 2 1
[ 3, 1, 2 ]
undefined
sort()
를 사용한다.JavaScript Array sort() Method
a.sort()
를 통해서, a의 배열이 정렬된 것을 확인할 수 있다. →[1,2,3]a.sort()
에서 sort 안에 들어가는 값이 양수, 음수, 0 인지에 따라서 정렬의 형태가 바뀐다.> a = [3,1,2]; function b(v1, v2){return v2-v1}; a.sort(b); console.log(a);
[ 3, 2, 1 ]
undefined
> a = [3,1,2]; function b(v1, v2){return v1-v2}; a.sort(b); console.log(a);
[ 1, 2, 3 ]
undefined
> a = [3,1,2]; function b(v1, v2){return 0}; a.sort(b); console.log(a);
[ 3, 1, 2 ]
undefined
// 를 통해서, 양수 음수 0 일 때 정렬의 순서가 바뀌는 것이 sort() 라는 것을 확인할 수 있다.
a.sort()
의 인자 부분에 함수를 넣을 수 있다.function b (v1, v2) { console.log('c', v1, v2); return 0;}; a.sort(b)
를 하게 될 경우, a.sort
의 인수에 함수 b 가 들어간 것을 볼 수 있다.function b
와 같이 인수 부분(sort())에 들어가는 함수를 콜백함수 라고 부른다.[JavaScript] 자바스크립트 콜백(callback)함수란?
콜백함수를 정의했지만, 콜백함수를 호출한 것은 우리가 아닌, sort() 라는 함수가 b 라는 함수를 호출하는 것이다.