Qin Xiaofu - 1 month ago 7x

Javascript Question

I have one function and I call it once,But when I run it in browser,It seems to run two times.

`function max() {`

console.log( arguments[0] );

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

*/

I want get the maximum value of an array,and I already know how to get it now.I just wonder why this function seems like execute twice and why this function can not get the right result.

Answer

Where `this`

refers to window object so int just calling the same function recursively since `window.max`

refers to the same function. On the second call, `this`

refers to `Math`

since you are defined `Math`

as this argument in `Fuction#apply`

. While calling max function recursively the first argument would be `1`

and `Array.from`

creates an empty array so `Math.max`

return `-Infinity`

as a result.

To make it work replace `this`

with `Math`

object although `Array.from`

is not necessary at all.

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

Or simply pass the array as a normal argument.

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

Source (Stackoverflow)

Comments