使用_.each创建数组

时间:2015-05-30 10:57:37

标签: javascript arrays functional-programming underscore.js each

我有这个练习来解决:

  

使用_.each从1,1000(含)

创建数组

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

你能帮助我吗?

2 个答案:

答案 0 :(得分:3)

您可以通过将所需的数组长度传递给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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

&#13;
&#13;
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(", "));
&#13;
<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>
&#13;
&#13;
&#13;

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

&#13;
&#13;
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(", "));
&#13;
<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>
&#13;
&#13;
&#13;

......但我确定这是在作弊。