【问题标题】:insert array in a underscore/lodash chain在下划线/lodash链中插入数组
【发布时间】:2016-12-22 04:48:40
【问题描述】:

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

例子:

  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();

我错过了什么?

【问题讨论】:

  • 虽然我从不使用 lodash 或任何我会尝试使用Array(maxValue) 而不是_(Array(maxValue))
  • 我认为tap 没有对您的退货声明做任何事情。我认为它只是给了你改变价值的机会。由于字符串是不可变的,这可能不是tap 的用例。
  • 是的,我误解了点击这里

标签: javascript underscore.js lodash


【解决方案1】:

1) _.tap 是可变参数,最好使用_.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();

【讨论】:

    【解决方案2】:

    您可以使用_.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>

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

    const str = "1,2,4";
    
    const result = Array.from({ length: Math.max(...str.split(',')) }, () => false);
    
    console.log(result);

    【讨论】:

      【解决方案3】:

      这里是纯 js 解决方案。

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

      【讨论】:

      • 纯 Javascript 的可读性不如 Lodash 版本。此外,某些函数可能会错过 Javascript,即使示例中不是这种情况。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      相关资源
      最近更新 更多