簡體   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