在 underscore/lodash 链中插入数组

insert array in a underscore/lodash chain

我正在尝试在 lodash/underscore 链中创建一个数组,但它不起作用。

示例:

  var foo = _.chain(currentValue) // let's say "1,2,4"
                .split(',')       // now it is [1,2,4]
                .max()            // now it is 4
                .tap(function(maxValue) {
                  return _(Array(maxValue)).fill(false);
                }) // should be now [false, false, false, false] but doesn't work
                .value();

我错过了什么?

这是纯 js 解决方案。

var str = "1,2,4";

var result = Array(Math.max.apply(null, str.split(','))).fill(false);
console.log(result)

您可以使用 _.times()_.fill():

var currentValue = "1,2,4";

var foo = _.chain(currentValue) // let's say "1,2,4"
  .split(',') // now it is ["1","2","4"]
  .max() // now it is "4"
  .times() // [undefined, undefined, undefined, undefined]
  .fill(false) // [false, false, false, false]
  .value();

console.log(foo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

并且没有使用 ES6 的 lodash Array#from:

const str = "1,2,4";

const result = Array.from({ length: Math.max(...str.split(',')) }, () => false);

console.log(result);

1) _.tap是mutate参数,最好用_.thru

2) 要获得链接的结果,您必须在链的末尾调用 .value()

3) 所以我的提议

_.chain('1,2,4')
    .split(',')      
    .max()           
    .thru(function(maxValue) {
        return _.chain(maxValue).times(_.constant(false)).value();
    })
    .value();

如果真的不需要_.tap_.thru

_.chain('1,2,4')
    .split(',')      
    .max()           
    .times(_.constant(false))
    .value();