2016-09-09 12 views
3

私は1つの機能を持っていますが、それを一度呼びますが、ブラウザで実行すると2回実行されるようです。適用コールに関連する問題

function max() { 
 
\t console.log(arguments[0]); 
 
\t return this.max.apply(Math, Array.from(arguments[0])); 
 
} 
 

 
console.log(max([1,32,42,1])); 
 

 
/* 
 
This is output of console: 
 
------------------------ 
 
[1, 32, 42, 1] 
 
1 
 
-Infinity 
 
*/

私は、配列の最大値を取得したい、と私はすでにそれがnow.Iただ不思議取得する方法を知っている理由は、この関数は、この関数は得ることができない理由を二回実行し、のように思えます適切な結果。

+0

'this'は' window'を参照し、 'global-functions'は' window-object'の 'properties'です。 '関数#apply'は' this'引数が 'called'関数の' this'コンテキストとして渡された関数を呼び出します – Rayon

+0

普通のパラメータだけではなく 'arguments [0]'を使用する特別な理由はありますか? –

答えて

1

ここで、thisはwindowオブジェクトを参照しているため、同じ関数を同じ関数を呼び出すだけで同じ関数を再帰的に呼び出すため、window.maxは同じ関数を参照します。 2番目の呼び出しでは、はMathを指します。Mathをこの引数としてFuction#applyに定義しているためです。 max関数を再帰的に呼び出すと、最初の引数は1になり、Array.fromは空の配列を作成します。その結果、Math.maxが返され、結果として-Infinityが返されます。

Mathオブジェクトに置き換えると、Array.fromは必要ありません。

function max() { 
    return Math.max.apply(Math,arguments[0]); 
} 

あるいは単に通常の引数として配列を渡します。この方法ではthis

function max(arr) { 
    return Math.max.apply(Math, arr); 
} 
+0

'Function#apply'のため – Rayon

+0

2番目の呼び出しは' Math.max([]) 'に等しくなりますか? – napoleonQin

+0

@QinXiaofuはい..... –

2

使用Math.max.apply

function max() { 
    //console.log(arguments[0]); 
    return Math.max.apply(Math, arguments[0]); 
} 
+1

'vals'は関数のパラメータで、' vals'を書くのではなく、 'Array.from(arguments [0])'のポイントは何ですか? –

+0

@torazaburoはい、Array.from(arguments [0]) 'の代わりに引数[0]をそのまま使用できます。 –

1
function max() { 
console.log(arguments[0]); 
return this.max.apply(Math, Array.from(arguments[0])); 
} 

@JaydipJは言及したようにウィンドウを指します。 Mathオブジェクトを渡したい場合。

function max(){ 
var x=this.max.apply(null,[0,1,2,3]); 
console.log(x); 
} 

max.apply(Math); 
関連する問題