JavaScriptのapplyをどこで使うのか
JavaScriptの関数によっては引数を幾つでも設定できるものがあります。例えばMath.maxです。この関数は引数で与えた数字の内、最大のものを返してくれる関数です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Math.max(1, 3, 5, 11, 7, 9) –> 11 |
しかし引数を動的に変更したい場合はどうしたらいいでしょうか。そこで使えるのがapplyになります。applyは引数を配列で与えられるようになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ary = [1, 3, 5, 11, 7, 9]; | |
Math.max.apply(null, ary) –> 11 |
最初の引数 null はthisとして何を与えるかになります。nullを与えた場合、thisはwindowオブジェクトになるようです。
自作関数で使う
自作関数の場合、多くは最後の引数をまとめたいと思うかも知れません。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function test(a, b, c, …args) { | |
console.log(a, b, c); | |
console.log(args); | |
} |
このようにしておくと、最初の3つの引数(a/b/c)には値が入り、残りの引数はargsにまとまります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test.apply(null, [1, 2, 3, 4, 5]); | |
–> 1,2,3 | |
–> [4, 5] |
引数を配列で準備しておくと、変数の定義が減るので扱いが楽になりそうです。元々配列で受け取れるようにしたり、オブジェクトで受け取ることで解決できそうですが、拡張していく中で徐々に引数が追加されてしまった場合(良くはないですが)はapplyを使えば解決できるでしょう。
コメントは受け付けていません。