0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

備忘録 Javascript callback関数

Posted at

callback関数 省略しないパターン

function arrayWalk(data, f) {
  //② dataにはarray fにはshowElementが格納
  for(var key in data) {
    //③引数で受け取ったshoElement関数を呼ぶ
    f(data[key], key);
  }
}

function showElement(value, key) {
  //④
  console.log(key + ':' + value);
}

var array = [1, 2, 3, 4, 5];
//①
arrayWalk(array, showElement);

callback 匿名関数

showElementを定義しない。

function arrayWalk(data, f) {
  for(var key in data) {
    f(data[key], key);
  }
}

var array = [1, 2, 3, 4, 5];
arrayWalk(array, function(value, key){
  console.log(key + ':' + value);
})

callback関数 ラムダ式

function arrayWalk(data, f) {
  for(var key in data) {
    f(data[key], key);
  }
}

var array = [1, 2, 3, 4, 5];
arrayWalk(array, (value, key) => {
  console.log(key + ':' + value);
})

動作結果

//0:1
//1:2
//2:3
//3:4
//4:5

参考

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで
https://gihyo.jp/book/2016/978-4-7741-8411-1

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?