繁体   English   中英

为什么过滤器 function 即使不通过条件也会返回数组

[英]Why filter function is returning array even when it does not pass the condition

我很难理解为什么这段代码不起作用。 它虽然使用一个小数据集。

const gl = wList.GreateLeague
const data = JSON.parse(fs.readFileSync("./raw/data.json"))
    
(function () {
  let glFinds = data.pokemons.filter((poke) => gl.hasOwnProperty(poke.pokemon_id))
  let ax = glFinds.filter((p) => {
    return gl[p.pokemon_id].stats.filter((ammo) => {
      return (
        p.attack === ammo[0] && p.defence === ammo[1] && p.stamina === ammo[2]
      );
    });
  });
  console.log(glFinds)
  console.log(ax)
})();

我的两个控制台的 output 是相同的,因此 ax 上的过滤器不起作用。 如果我包含比data.json更小的testData.json ,则 ax 工作正常。

编辑:统计数据看起来像这样。 这里 [0],[1],[2] 是攻击防御和耐力

"stats": [
          [1, 15, 15, 20.5, 1494],
          [0, 13, 11, 20.5, 1494],
          [2, 14, 15, 20.5, 1494],
          [0, 10, 15, 20.5, 1494],
          [1, 12, 11, 20.5, 1494],
          [0, 15, 15, 20.5, 1494],
          [3, 13, 15, 20.5, 1494],
          [0, 14, 10, 20.5, 1494],
          [2, 15, 14, 20.5, 1494],
          [0, 11, 13, 20.5, 1494]
        ],

我的数据文件有这样的对象数组:

{
      "pokemon_id": 155,
      "attack": 2,
      "defence": 5,
      "stamina": 0,
      "move1": 209,
      "move2": 125,
      "level": 4,
    }

我正在尝试过滤与统计数组的(0,1,2 索引)匹配的任何 object,对象的攻击、防御和耐力必须匹配任何统计数组的前 3 个元素。

filter内部的 function 必须返回truefalse ,具体取决于当前项目是否应包含在 output 数组中。 但是正如 Andreas 已经指出的那样,您的 function 返回gl[p.pokemon_id].stats.filter(...) ,这是一个数组。

当尝试将数组评估为truefalse时,它会被视为true (即使它为空),因此您的整个filter过程实际上什么都不做。

if ([]) console.log(true);
// true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM