ES6 - generate an array of numbers

前端 未结 6 792
我寻月下人不归
我寻月下人不归 2021-01-31 08:03

Having googled for it I found two solutions:

6条回答
  •  我在风中等你
    2021-01-31 08:47

    It seems the problem is that codepen precompiles your code using babel es2015-loose.

    In that mode, your

    [...Array(10).keys()];
    

    becomes

    [].concat(Array(10).keys());
    

    And that's why you see an array containing an iterator.

    With es2015 mode you would get

    function _toConsumableArray(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }
        return arr2;
      } else {
        return Array.from(arr);
      }
    }
    [].concat(_toConsumableArray(Array(10).keys()));
    

    which would behave as desired.

    See ②ality - Babel 6: loose mode for more information about the modes.

提交回复
热议问题