“RangeError: Maximum call stack size exceeded” Why?

后端 未结 4 409
攒了一身酷
攒了一身酷 2020-12-02 14:59

If I run

Array.apply(null, new Array(1000000)).map(Math.random);

on Chrome 33, I get

RangeError: Maximum call

4条回答
  •  渐次进展
    2020-12-02 16:00

    The answer with for is correct, but if you really want to use functional style avoiding for statement - you can use the following instead of your expression:

    Array.from(Array(1000000), () => Math.random());

    The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.

    Following the same idea you can rewrite it using ES2015 Spread operator:

    [...Array(1000000)].map(() => Math.random())

    In both examples you can get an index of the iteration if you need, for example:

    [...Array(1000000)].map((_, i) => i + Math.random())

提交回复
热议问题