Callback function
Callback function ์ด๋? - MDN
: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of rotine or action.
์ฝ๋ฐฑ ํจ์(A)๋ ๋ค๋ฅธ ํจ์(B)์ ์ธ์๋ก ๋๊ฒจ์ง๋ ํจ์๋ก,
๋ค๋ฅธ ํจ์(B)์ ๋ด๋ถ์์ ์คํ๋๋ ํจ์(A)๋ฅผ ๋งํ๋ค.
1. map()
Returns a new array containing the results of calling callbackFn
on every element in this array.
ex)
Copy [ '1' , '2' , '3' ] .map (Number)
const numbers = [ 0 , 9 , 99 ]
function addOne (number) {
return number + 1
}
const newNumbers1 = numbers .map (addOne)
console .log (newNumbers1)
const newNumbers2 = numbers .map ( function (number) {
// [0, 9, 99] ๋ฅผ ์ํํ๋ฉฐ, ๊ฐ ์์๋ฅผ (number) ์๋ฆฌ์ ๋ฃ๋๋ค.
// ๊ทธ๋ฆฌ๊ณ ๋ฆฌํด๋ ๊ฐ์ ์๋ก์ด ๋ฐฐ์ด์ ๋ฃ๊ณ ๋ง์ง๋ง์ ๋ฆฌํดํ๋ค.
return number + 1
})
console .log (newNumbers2)
2. forEach()
Calls a callback function for each element in the array.
ex)
Copy // 2. forEach
// : return ๊ฐ์ด ์๋ค!
let sum = 0
nums = [ 1 , 2 , 3 ]
nums .forEach ( function (number){
// numbers์ ๊ฐ ์์๋ฅผ number ์๋ฆฌ์ ๋ฃ๊ณ ,
// ๋๋จธ์ง๋ ์์์ ํด๋ผ! return ์๋ค!
sum += number
})
console .log ( '๋ฐ?' + nums)
3. filter()
Returns the found element in the array, if some element in the array satisfies the testing callback function, or undefined if not found.
ex)
Copy // 3. filter
const odds = [ 1 , 2 , 3 ] .filter ( function (number) {
// ๊ฐ ์์๋ฅผ number ์๋ฆฌ์ ๋ฃ๊ณ ,
// return์ด true์ธ ์์๋ค๋ง ๋ชจ์์ ์๋ก์ด ๋ฐฐ์ด๋ก return
return number % 2
})
console .log (odds)
4. find()
Returns the found element in the array, if some element in the array satisfies the testing callback function, or undefined if not found.
ex)
Copy // 4. find
const evens = [ 1 , 2 , 3 , 4 ] .find ( function (number) {
// filter()์๋ ๋ค๋ฅด๊ฒ find()๋ ํจ์๊ฐ true๋ฅผ returnํ๋ฉด ๋ฐ๋ก ์ข
๋ฃ๋จ
return ! (number & 1 )
})
console .log ( '์ง์ ์ฐพ์๋ผ~ ' , evens)
5. every()
Returns true if every element in this array satisfies the testing callback function
ex)
Copy // 5. every
const pass = [ 50 , 60 , 70 , 80 , 90 ] .every ( function (number){
// ๋ชจ๋ ์์๋ค์ด ์กฐ๊ฑด์ ํต๊ณผํ๋ฉด true, ์๋๋ฉด false return
return number > 40
})
console .log ( 'ํต๊ณผ์
๋๊น? ' , pass)