使用 _.each 创建数组

Create array using _.each

我要解决这个练习:

Use _.each to create an array from 1, 1000 (inclusive)

我真的不知道该怎么做,我认为这不可能...

你能帮帮我吗?

您可以通过将所需的数组长度传递给 Array 构造函数来创建一个包含 1000 个元素的空数组,然后使用 _.each() 为数组中的每个索引赋值。

var array = _.each(new Array(1000), function(v, i, a) {
  a[i] = i + 1;
});
console.log(array)
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

问题上的functional-programming标签就是线索。 :-) 在函数式编程中,循环通常写成递归。那么我们如何使用递归来构建一个使用_.each的数组呢?通过回调调用它:

var array = _.each([1], function cb(e, i, a) {
  if (a.length < 1000) {
    a.push(a.length + 1);
    _.each(a, cb);
  }
});
snippet.log(array.length);
snippet.log(array.join(", "));
<script src="http://underscorejs.org/underscore-min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

或者真的调皮,我们可以从 1000 个字符的字符串开始:

var oneThousand = 
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789" +
    "01234567890123456789012345678901234567890123456789";
var array = [];
_.each(oneThousand, function(e, i) {
  array[i] = i + 1;
});
snippet.log(array.length);
snippet.log(array.join(", "));
<script src="http://underscorejs.org/underscore-min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

...但我确定那是作弊。