簡體   English   中英

為什么我不能連接這一系列的lodash電話?

[英]Why can't I chain this series of lodash calls?

這段代碼:

  _(gameState.loot)
  .pick((value, key) -> key isnt "pickUpAnimations")
  .filter ((d) -> _.isArray (d))
  .reduce ((sum, d) -> sum.concat (d))

給我這個錯誤:

TypeError: 'undefined' is not a function (evaluating '(function(d) {

這段代碼工作正常:

  removedAnimations = _.pick(gameState.loot, (value, key) -> key isnt "pickUpAnimations")
  removedAnimations = _.filter removedAnimations, ((d) -> _.isArray (d))
  removedAnimations = _.reduce removedAnimations, ((sum, d) -> sum.concat (d))
  removedAnimations

對我而言,似乎這些應該做同樣的事情。 gameState.loot的架構如下所示:

loot: {
  ttl: 6000
  slowBlinkWhenTtlLessThanPercent: 60
  fastBlinkWhenTtlLessThanPercent: 30
  resurrections: []
  gold: []
  health: []
  equipment: []
  pickUpAnimations: []
}

順便說一句,這是從第一個例子生成的javascript:

return _(gameState.loot).pick(function(value, key) {
  return key !== "pickUpAnimations";
}).filter((function(d) {
  return _.isArray(d);
}).reduce((function(sum, d) {
  return sum.concat(d);
})));

我試過@Blender的建議:

  _(gameState.loot)
    .pick (value, key) -> key isnt "pickUpAnimations"
    .filter (d) -> _.isArray (d)
    .reduce (sum, d) -> sum.concat (d)

但這給了我這個錯誤:

>> TypeError: 'undefined' is not a function (evaluating '"pickUpAnimations".filter(function(d) {

這是javascript的樣子:

return _(gameState.loot).pick(function(value, key) {
  return key !== "pickUpAnimations".filter(function(d) {
    return _.isArray(d.reduce(function(sum, d) {
      return sum.concat(d);
    }));
  });
});

這是生成的JavaScript更好的縮進:

_(gameState.loot).pick(function(value, key) {
    return key !== "pickUpAnimations";
}).filter(
    (function(d) {
        return _.isArray(d);
    }).reduce((function(sum, d) {
        return sum.concat(d);
    }))
);

如您所見, .filter (....filter(...不一樣。兩種可能的修復:

  1. 刪除方法名稱和左括號之間的空格:

     _(gameState.loot) .pick((value, key) -> key isnt "pickUpAnimations") .filter((d) -> _.isArray (d)) .reduce((sum, d) -> sum.concat (d)) 
  2. 完全刪除括號:

     _(gameState.loot) .pick (value, key) -> key isnt "pickUpAnimations" .filter (d) -> _.isArray (d) .reduce (sum, d) -> sum.concat (d) 

你也可以擺脫調用_.isArray的匿名函數:

    _(gameState.loot)
        .pick (value, key) -> key isnt "pickUpAnimations"
        .filter _.isArray
        .reduce (sum, d) -> sum.concat (d)

coffeescript的暗邊:

_(gameState.loot).pick(function(value, key) {
  return key !== "pickUpAnimations";
}).filter((function(d) {
  return _.isArray(d);
}).reduce((function(sum, d) {
  return sum.concat(d);
})));

注意額外的(在你的過濾器回調之前。你正在調用的是:

(function(d) { return _.isArray(d); }).reduce(...

哪個會失敗。 修復你的curlies,你很高興。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM