01. ๐ฆ foreach, map ๋ถ์
๐ ์ธํฐํ์ด์ค์ ์ ๋๋ฆญ
interface A<T>
๐ ํ์ ์ ์ ๋๋ฆญ
type A<T>
๐ class์ ์ ๋๋ฆญ
class A<T>
๐ ํ์ ์ถ๋ก
foreach๋ ์ ๋๋ฆญ์ ์ด์ฉํ์ฌ, ํ์ ์ถ๋ก ์ด ๊ฐ๋ฅํ๋ค.
// value: number
[1, 2, 3]
.forEach((value) => {
console.log(value);
})
[
// value: string
("1", "2", "3")
].forEach((value) => {
console.log(value);
})
[
// value: boolean
(true, false, true)
].forEach((value) => {
console.log(value);
})
[
// value : number | string | boolean
(123, "123", true)
].forEach((value) => {
console.log(value);
});
๐ ์ ๋๋ฆญ์ ์ฌ์ฉํ๋ ์ด์
// ํ์
์ด ํ๊ฐ์ง๋ผ๊ณ ์ถ๋ก ์ด ๋ถ๊ฐ๋ฅํจ
// 2*2 ์ด 4๊ฐ์ง์ ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ๊ณ์ฐํด์ ์ฌ์ฉํ ์ ์์
function numOrStrAdd(a: number | string, b: number | string) {
return a + b;
}
๐ forEach ๋ถ์
//lib.es5.d.ts
interface Array`<T>` {
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
* ๋ฐฐ์ด์ ๊ฐ ์์์ ๋ํด ์ง์ ๋ ์์
์ ์ํํฉ๋๋ค.
* @param callbackfn ์ต๋ ์ธ ๊ฐ์ ์ธ์๋ฅผ ํ์ฉํ๋ ํจ์์
๋๋ค. ๊ฐ๊ฐ์ ๋ํด ๋ฐฐ์ด์ ๊ฐ ์์์ ๋ํด ํ ๋ฒ์ฉ callbackfn ํจ์๋ฅผ ํธ์ถํฉ๋๋ค.
* @param thisArg ์ด ํค์๋๊ฐ callbackfn ํจ์์์ ์ฐธ์กฐํ ์ ์๋ ๊ฐ์ฒด์
๋๋ค. ์ด Arg๋ฅผ ์๋ตํ๋ฉด undefined ๊ฐ์ด ์ด ๊ฐ์ผ๋ก ์ฌ์ฉ๋ฉ๋๋ค.
*/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
}
- interface Array
<T>
์ forEach๊ฐ ์ ์ธ๋์ด ์์ต๋๋ค. - CallBackfn ํจ์๋ callbackfn: (value: T, index: number, array: T[])
- value: T์ array: T[]๊ฐ Array
<T>
์ ์ ๋๋ฆญ์ ํจ๊ป ๊ณต์ ํ๋ ๊ฒ์ด ํ์ธ ๊ฐ๋ฅํฉ๋๋ค.
๐ map ๋ถ์
interface Array`<T>` {
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
* ๋ฐฐ์ด์ ๊ฐ ์์์์ ์ ์๋ ์ฝ๋ฐฑ ํจ์๋ฅผ ํธ์ถํ๊ณ ๊ฒฐ๊ณผ๊ฐ ํฌํจ๋ ๋ฐฐ์ด์ ๋ฐํํฉ๋๋ค.
* @param callbackfn ์ต๋ ์ธ ๊ฐ์ ์ธ์๋ฅผ ํ์ฉํ๋ ํจ์์
๋๋ค. ๊ฐ๊ฐ์ ๋ํด ๋ฐฐ์ด์ ๊ฐ ์์์ ๋ํด ํ ๋ฒ์ฉ callbackfn ํจ์๋ฅผ ํธ์ถํฉ๋๋ค.
* @param thisArg ์ด ํค์๋๊ฐ callbackfn ํจ์์์ ์ฐธ์กฐํ ์ ์๋ ๊ฐ์ฒด์
๋๋ค. ์ด Arg๋ฅผ ์๋ตํ๋ฉด undefined ๊ฐ์ด ์ด ๊ฐ์ผ๋ก ์ฌ์ฉ๋ฉ๋๋ค.
*/
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
}
- interface Array
<T>
์ map์ด ์ ์ธ๋์ด ์์ต๋๋ค. - CallBackfn ํจ์๋ callbackfn: (value: T, index: number, array: T[])
- value: T์ array: T[]๊ฐ Array
<T>
์ ์ ๋๋ฆญ์ ํจ๊ป ๊ณต์ ํ๋ ๊ฒ์ด ํ์ธ ๊ฐ๋ฅํฉ๋๋ค.
- value: T์ array: T[]๊ฐ Array
- callbackfn(~) => U
- T์ ๋ค๋ฅธ ์ ๋๋ฆญ U๋ฅผ ์ฌ์ฉํ ๊ฒ์ ํ์ธํ ์์์ต๋๋ค.
- T์๋ ํ์ ์ด ๋ค๋ฅผ ์ ์๋ค๋ ์๋ฏธ์ด๋ฉฐ,
- map์ ์ฒ๋ฆฌ๊ฒฐ๊ณผ๊ฐ U[] ๋ฐฐ์ด์ธ ๊ฒ์ ํ์ธํ ์ ์์ต๋๋ค.
Last updated on