2
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 1 year has passed since last update.

JavaScript関数の5つの定義

Last updated at Posted at 2023-01-19

JSに関数の記述いくつがあって,使い方を把握するように,ここに書いておきます.参考になれると幸いです.

①まず,通常の定義は
    function exp(x1,x2){
    ...
    }
②即時実行関数式(定義すると同時に実行される)
//場合によって,関数名を省略可能
const s1 = function(x){ return x*x};
s1(2)  //出力=4

//回帰の場合に,関数名が必要 
const s2 = function f1(x){ if (x <=1) return 1; else return x * f1(x-1);}
s2(4)  //出力=24

//即変数に値を与えるのも可能
const s3 = function(x){ return x*x}(3); //s3 = 9

//別の関数の引数にもなれる
function t(x){return x*x}
t(function(a,b){return a-b}(2,3))  //出力=1

③Arrow関数
Arrow関数は②の関数の簡潔化と思われる
//functionを省略 
var sum = (x,y) => {return x+y};
//関数体に,returnしか存在しない時,return を省略できる 
var sum = (x,y) => x+y;
//引数が1個のみ時,"()"を省略できる
var sum = x => x*x;
//注意,引数がない時,引数の"()"は必要
var sum x = () => 1; 
④可変長引数
関数の引数の数が特定しないとき,可変長引数(rest parameter)を使う
//functionを省略 
function f(...r){
    for (let n of r){ consol.log(n)}
}
f(1,2,3,4,5,6) //1,2,3,4,5,6

//上記引数中の"..."は配列Arrayの"..."と同じものではない
//配列の"..."は,配列を自動分解するキーワードである 
var a = [1,2,3,4];
f(a);     //[1,2,3,4]
f(...a);  //1 2 3 4
⑤関数を値として変数として使う
//functionを省略 
function fun1(r){
    return r + r;
}
var a = fun1(2);  //a = 4
var b = fun1;
b(2)             //4
fun1(2)         //4
2
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
2
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?