简体   繁体   English

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

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

I'm struggling to understand why this code is not working.我很难理解为什么这段代码不起作用。 its working with a small dataset though.它虽然使用一个小数据集。

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

my output for both console is same, therefore filter on ax is not working.我的两个控制台的 output 是相同的,因此 ax 上的过滤器不起作用。 ax is working fine if I include testData.json which is a smaller then data.json .如果我包含比data.json更小的testData.json ,则 ax 工作正常。

edit: stats look like this.编辑:统计数据看起来像这样。 here [0],[1],[2] are the attack defense and stamina这里 [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]
        ],

my data files have array of objects like this:我的数据文件有这样的对象数组:

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

I am trying to filter any object that matches (0,1,2 index) of stats array, object's attack, defense and stamina must match any of the stats array first 3 element.我正在尝试过滤与统计数组的(0,1,2 索引)匹配的任何 object,对象的攻击、防御和耐力必须匹配任何统计数组的前 3 个元素。

The function inside filter must return true or false , depending on whether the current item shall be included in the output array or not. filter内部的 function 必须返回truefalse ,具体取决于当前项目是否应包含在 output 数组中。 But your function returns gl[p.pokemon_id].stats.filter(...) , which is an array, as Andreas already pointed out.但是正如 Andreas 已经指出的那样,您的 function 返回gl[p.pokemon_id].stats.filter(...) ,这是一个数组。

When trying to evaluate an array as true or false , it counts as true (even if it is empty), therefore your whole filter procedure effectively does nothing.当尝试将数组评估为truefalse时,它会被视为true (即使它为空),因此您的整个filter过程实际上什么都不做。

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

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

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