### 無名関数
– 関数名がないもの
const f = function(name:string):void {
console.log("hello, " + name)
}
f("taro")
f("hanako")
### アロー関数
(引数): 戻り値 => 実行する処理
const f = (name:string):void => {
console.log("hello, " + name)
}
console.log(typeof(f)) とすると “function” がreturnとなる
### 内部関数
関数の中でしか使えない関数
const f = (n:number)=> {
const inF = (n:number):void => {
console.log("value:" + n)
}
let total = 0
for (let i = 1; i<= n; i++){
total += i
inF(total)
}
}
f(10)
### 引数に関数を使う
const func = (n:number, f:Function):void => {
let res = f(n)
console.log("Result:" + res)
}
const double = (n:number) => n * 2
const total = (n:number) => {
let total = 0
for (let i = 1; i <= n; i++)
total += i
return total
}
const num = 100
func(num, double)
func(num, total)
### 数値とテキストの関数を引数にする
charAtは「●文字目」を得るもの
const func = (n:number, f:(n:number)=>number|string):void => {
let res = f(n)
console.log("Result:" + res)
}
const double = (n:number) => n * 2
const word = (n:number):string => {
const w = ['〇','一','二','三','四','五','六','七','八','九']
const s = String(n)
let res:String[] = []
for(let i = 0; i< s.length; i++){
let c = s.charAt(i)
res.push(w[Number(c)])
}
return res.join('')
}
const num = 1230
func(num, double)
func(num, word)
### 戻り値に関数を使う
const f = (tax:number):(n:number)=> number => {
return (n:number)=> n * (1 +tax)
}
const f1 = f(0.1)
const f2 = f(0.8)
const price = 123400
console.log(f1(price))
console.log(f2(price))
### クロージャー
定義された環境を保ち、その中で動く関数をクロージャという
const f = (n:number):() => number => {
let count:number = 0
return ():number => {
count += n
return count
}
}
const f1 = f(1)
const f2 = f(2)
const f3 = f(3)
for(let i = 0; i < 10; i++){
console.log(f1() + '\t' + f2() + '\t' + f3())
}
ちょっと難しくなってきた