2017-11-28 4 views
-4

私は聞いたforEach 3つのパラメータを取得する関数を必要とする、どのようなスタイルは、4のパラメータを定義した。なぜそれが働くのですか?これは、JavaScriptを書くための最善の方法ですForEach

let arr = ["A", "B", "C", "D"]; 

//1 
function temp(value, index, arr) { 
    console.log(value); 
} 

arr.forEach(temp); 

//2 
arr.forEach(function(value, index, arr) { 
    console.log(value); 
}); 

//3 
arr.forEach((value, index, arr) => { 
    console.log(value); 
}); 


//4 
arr.forEach(e => 
{ 
    console.log(e); 
}); 
+0

それはjavascriptのだから。それは多くのarityをチェックしません。 –

答えて

0

関数定義は、引数が渡される変数の名前を定義します。

これがすべてです。

渡すことができる引数の数を強制しません。

任意の数の引数を任意の関数に渡すことができます。

一部の引数は無視される可能性があります。

function myFunction(a, b, c) { 
 
    console.log("My function with " + arguments.length + " arguments"); 
 
    console.log(a, b, c); 
 
    for (var i = 0; i < arguments.length; i++) { 
 
    console.log("Argument " + i + " is " + arguments[i]); 
 
    } 
 
} 
 

 
myFunction(100); 
 
myFunction(200, 300, 400, 500, 600, 700); 
 

 
function myFunctionWhichChecks(a, b, c) { 
 
    if (arguments.length !== 3) { 
 
    throw new Error("myFunctionWhichChecks must have exactly 3 arguments"); 
 
    } 
 
    console.log("My function which checks has " + arguments.length + " arguments"); 
 

 

 
} 
 

 
myFunctionWhichChecks(800, 900, 1000); 
 
myFunctionWhichChecks(800, 900, 1000, 1100);

関連する問題